Fork me on GitHub
#re-frame
<
2020-04-21
>
otwieracz14:04:16

Hey! Where can I find any examples of interceptors injecting coeffects?

p-himik14:04:38

Here's some simple example that should work:

(->interceptor
  :id :add-cofx
  :before (fn [ctx]
            (assoc-coeffect ctx :my-cofx "hello")))

otwieracz14:04:13

OK, so it will be (assoc-coeffect ctx :cookie/get [:token])

otwieracz14:04:34

OK, something isn't working - probably I don't understand something. I was doing:

(rf/reg-event-fx :authenticate
                 [(rf/inject-cofx :cookie/get [:token])]
                 (fn [{cookie :cookie/get} _]
                   {:http-xhrio {:method :get
                                 :uri (api/api "logged-in")
                                 :headers "Authorization" (str "Token " (:token cookie))}
                                 :response-format (ajax/transit-response-format)
                                 :on-success [:save-user-name]
                                 :on-failure [:clear-auth]}})
What I am trying to do is to create an interceptor:
(def with-auth
  (rf/->interceptor
   :id :with-auth
   :before (fn [ctx]
             (rf/assoc-coeffect ctx :cookie/get [:token]))
   :after (fn [ctx]
            (js/console.log ctx)
            (-> (assoc-in ctx
                          [:effects :http-xhrio :headers "Authorization"]
                          (str "Token" (get-in ctx [:cookie/get :token])))))))

otwieracz14:04:40

But there is no :cookie/get in ctx

p-himik14:04:18

I don't understand what you want to end up with. inject-cofx creates an interceptor that injects a cofx derived from a function previously registered with reg-cofx. rf/->interceptor creates a different interceptor that can do anything you want. It's not related to reg-cofx in any way.

p-himik14:04:16

Just check their source code. :) The whole re-frame codebase is not that complicated. And where it is, there are abundant comments.

otwieracz15:04:12

OK, so

(def with-auth
  (rf/->interceptor
   :id :with-auth
   :before (fn [ctx]
             (update ctx :coeffects (registrar/get-handler :cofx :cookie/get) [:token]))
   :after (fn [ctx]
            (-> (assoc-in ctx
                          [:effects :http-xhrio :headers "Authorization"]
                          (str "Token " (get-in ctx [:coeffects :cookie/get :token]))))))) 

otwieracz15:04:48

seems to do the trick. But isn't this bad practice?

otwieracz15:04:49

I am replicating parts of inject-cofx , using something outside of re-frame.core - I don't want to be doing inventing wheel again 🙂

p-himik15:04:42

Is :cookie/get defined in your own code?

p-himik16:04:17

Ah, then your usage seems fine! The only thing I'd change is probably cache the call to registrar/get-handler outside of that fn with a let. But it's not that important.

p-himik16:04:13

I have something like that with :http-xhrio as well. I don't like the long name and some defaults so I write it in my own effect.