Sha256: b83ee30ca5c57507a36e7f2bd65cb66108c4fe8fdd8c155de15ff4c9123aa430
Contents?: true
Size: 1.15 KB
Versions: 1
Compression:
Stored size: 1.15 KB
Contents
module Quandl module Cassinatra module Middleware class ParseJSON < Faraday::Response::Middleware def on_complete(env) env[:body] = case env[:status] when 204 parse('{}', env) else parse(env[:body], env) end end def parse(body, env) json = parse_json(body, env) errors = json.delete(:errors) || {} metadata = json.delete(:metadata) || {} # collect some response data metadata.merge!({ status: env[:status], headers: env[:response_headers], }) # return object object = { :data => json, :errors => errors, :metadata => metadata } env[:status] = 200 object end def parse_json(body = nil, env) body ||= '{}' json = begin Yajl.load(body, :symbolize_keys => true) rescue Yajl::ParseError nil end # invalid json body? if json.blank? # fallback to error message json = { id: 1, errors: { parse_error: "Invalid Cassinatra API response. status: #{env[:status]} (last JSON response was #{body.inspect})" } } end json end end end end end
Version data entries
1 entries across 1 versions & 1 rubygems
Version | Path |
---|---|
quandl_cassinatra-0.1.15 | lib/quandl/cassinatra/middleware/parse_json.rb |