Sha256: 7eea0d8de0c6434f053304c8039d2446eded8c4a083a6ab9b5f5faa8de43c70c

Contents?: true

Size: 1.51 KB

Versions: 9

Compression:

Stored size: 1.51 KB

Contents

module Startback
  module Web
    class Api < Sinatra::Base
      include Support
      include Errors

      set :raise_errors, true
      set :show_exceptions, false

    protected

      ###
      ### Facade over context
      ###

      def context
        env[Startback::Context::Middleware::RACK_ENV_KEY]
      end

      ###
      ### Facade over third party tools
      ###
      include Support::OperationRunner

      def operation_world(op)
        { context: context }
      end

      ###
      ### About the body / input
      ###

      def loaded_body
        @loaded_body ||= case ctype = request.content_type
        when /json/
          json_body
        when /multipart\/form-data/
          file = params[:file]
          file_body file, Path(file[:filename]).extname
        else
          unsupported_media_type_error!(ctype)
        end
      end

      def json_body(body = request.body.read)
        JSON.load(body)
      end

      def file_body(file, ctype)
        raise UnsupportedMediaTypeError, "Unable to use `#{ctype}` as input data"
      end

      ###
      ### Various reusable responses
      ###

      def serve_nothing
        [ 204, {}, [] ]
      end

      def serve(entity_description, entity, ct = :json)
        if entity.nil?
          status 404
          content_type :json
          { description: "#{entity_description} not found" }.to_json
        else
          content_type ct
          entity.to_json
        end
      end

    end # class Api
  end # module Web
end # module Startback

Version data entries

9 entries across 9 versions & 1 rubygems

Version Path
startback-0.7.1 lib/startback/web/api.rb
startback-0.7.0 lib/startback/web/api.rb
startback-0.6.0 lib/startback/web/api.rb
startback-0.5.5 lib/startback/web/api.rb
startback-0.5.4 lib/startback/web/api.rb
startback-0.5.3 lib/startback/web/api.rb
startback-0.5.2 lib/startback/web/api.rb
startback-0.5.1 lib/startback/web/api.rb
startback-0.5.0 lib/startback/web/api.rb