Sha256: b6185e957459cf3a238a7b7f6e20fb6fe5010d4abf037cbb9a492ae38f1d48a6

Contents?: true

Size: 1 KB

Versions: 2

Compression:

Stored size: 1 KB

Contents

require 'json'
require 'mustermann'

module EsReadModel

  class Api

    def initialize(routes)
      @routes = routes
    end

    def call(env)
      @request = Rack::Request.new(env)
      path = @request.path_info
      @routes.each do |route, handler|
        pattern = Mustermann.new(route)
        args = pattern.params(path)
        if args
          return json_response(503, {status: env['readmodel.status']}) unless env['readmodel.available'] == true
          result = handler.call(@request.env['readmodel.state'], @request.params.merge(args))
          return result ? json_response(200, result) : json_response(404, {error: 'not found'})
        end
      end
      return json_response(404, {error: 'not found'})
    end

    private

    def json_response(status_code, body)
      result = body.merge({
        _links: { self: @request.fullpath }
      })
      [
        status_code,
        {
          'Content-Type' => 'application/json'
        },
        [result.to_json]
      ]
    end

  end

end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
es-readmodel-0.0.4 lib/es_readmodel/api.rb
es-readmodel-0.0.1 lib/es_readmodel/api.rb