Sha256: 5378d1755a463beafc6bcd6cd6267ba05b39b9ddd2308ee4dad870b9c5e8dee5
Contents?: true
Size: 1.61 KB
Versions: 1
Compression:
Stored size: 1.61 KB
Contents
require 'rack' require 'json' require 'mustermann' module EsReadModel class ApiError < StandardError end 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| args = Mustermann.new(route).params(path) return invoke_handler(handler, args, env) if args end return json_response(404, {error: 'path did not match any route'}) end private def invoke_handler(handler, args, env) return json_response(503, {status: env['readmodel.status']}) unless env['readmodel.available'] == true params = @request.params.merge(args) begin payload = @request.body.read body = payload.empty? ? {} : JSON.parse(payload, symbolize_names: true) params = params.merge(body) result = handler.call(@request.env['readmodel.state'], params) return result ? json_response(200, result) : json_response(404, {error: 'not found in read model'}) rescue ApiError => ex return json_response(400, { error: ex.message }) rescue Exception => ex return json_response(500, { error: "#{ex.class.name}: #{ex.message}", backtrace: ex.backtrace, params: params }) end end 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
1 entries across 1 versions & 1 rubygems
Version | Path |
---|---|
es-readmodel-0.0.9 | lib/es_readmodel/api.rb |