r0man / cljs-http

A ClojureScript HTTP library.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Support custom middlewares

lacogubik opened this issue · comments

Clj-http supports custom middlewares (e.g. to be able to set default headers for all the requests), it would be nice if cljs-http would support it as well.

@r0man recently merged a PR that I submitted which adds a middleware to set the default headers: #45

Could you give a code example of how you would like the custom middleware api to look like? I agree that this may be a desirable feature.

Maybe something like this? https://github.com/dakrone/clj-http#custom-middleware-lists

Although this might still not solve default header issue. Yes, I had a look at your PR, but my understanding is that you still need to provide :default-headers map on each call.

Ideal behaviour for my use case would be to set default headers once, and then just be able to call library methods for get,post etc, without the need to provide default headers.

@lacogubik - one solution for this is to create a client with the middlewares that you want to use, but you will have to redefine the convenience methods eg: get post delete to use your client, eg:

(ns my-ns.http
  (:require [cljs-http.client :as client]))

(def client-with-csrf
  (wrap-default-headers client/request {"x-csrf-token" "abc123"}))

(defn get
  "Like #'request, but sets the :method and :url as appropriate."
  [url & [req]]
  (client-with-csrf (merge req {:method :get :url url})))

Your proposed idea looks nice, let's see what @r0man thinks

@brentvatne Thanks, that is exactly what we did, but I would hope there could be better way, rather then redefining all the methods.

commented

I think the ideal solution would be to enhance the get, post,
etc, functions to use the default client if the first argument is
a string/url, and also accept a custom client as first
argument. So those 2 calls would be possible.

(http/get "http://example.com" {:query-params {:q "x"})
(http/get my-client "http://example.com" {:query-params {:q "x"})

This is also a problem in clj-http. @dakrone Any thoughts about this?
Would you be open to such behaviour in clj-http?

@r0man - I like that solution, should I throw a pull request together or would you like to wait on some consensus from @dakrone in order to keep consistent with clj-http?

commented

PR with tests welcome ...

@r0man I'd be fine with passing in a client to the get, post, put, etc methods