Created
November 10, 2012 17:54
-
-
Save kgrz/4051902 to your computer and use it in GitHub Desktop.
Using Faraday and making CouchDB return JSON. Simple middleware
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # this simple plumbing makes sure that the return data is in the form of a hash. | |
| require 'faraday' | |
| class Main | |
| attr_reader :conn | |
| def initialize | |
| @conn = Faraday.new "http://127.0.0.1:5984/somedb" do |faraday| | |
| faraday.adapter :em_http | |
| faraday.builder.insert(0, JSONMiddleware) | |
| end | |
| end | |
| def db_stats | |
| conn.get.body | |
| end | |
| end | |
| class JSONMiddleware | |
| def initialize(app) | |
| @app = app | |
| end | |
| def call(env) | |
| # request non-sense goes here | |
| @app.call(env).on_complete do |env| | |
| env[:body] = env[:body].strip.empty? JSON.parse "{}" : JSON.parse env[:body] | |
| env[:response_headers]["Content-Type"] = 'application/json' | |
| env[:response_headers]["Content-Length"] = env[:body].length.to_s | |
| end | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment