Fork me on GitHub
#liberator
<
2018-02-26
>
benzap05:02:12

Hey guys, so i'm trying to a template for a restful api, and i'm running into an issue involving the different resource handles

benzap05:02:42

within my (defresource, I want to handle an unauthorized access, but I want to also respect the Accepts: datatype similar to how the :handle-ok handler works

benzap05:02:05

Currently, if i set my handler as :handle-unauthorized (fn [_] {:type :error :message "unauthorized"}) it produces an internal error

benzap05:02:35

err woops, it's a bit different, the function being sent is more like (fn [_] {:message (payload/error "Unauthorized Access" :type ::unauthorized-access)}) which generates a payload with keys :data, :data-type :payload-type and :extra

benzap05:02:12

but this causes an arity error, my guess is the handler is trying to incorporate it within the context similar to the other handlers and actions

benzap05:02:51

Looking over the, code it seems like handle-ok is implemented using defhandler, along with handle-unauthorized, yet the return of handle-ok acts completely different from the rest of the handlers. Am I missing something?

ordnungswidrig07:02:06

@benzap this is a fundamental flaw with liberator’s response creation, because, when handle-unauthorized is called, the media-type is not yet negotiated. Issue #275 is related, https://github.com/clojure-liberator/liberator/issues/275

ordnungswidrig08:02:13

Another solution is define :as-response and wrap liberator.reponse/as-response and set a default media-type in the context:

(defresource hmmm
...
:as-response (fn [d ctx] (liberator.representation/as-response d (update-in ctx [:representation :media-type] #(or % "application/json"))))
...

benzap08:02:32

@ordnungswidrig thanks, I ended up just returning a string, but now I guess i'll rethink it 🙂

ordnungswidrig08:02:21

This issue is bugging me for a while, but I did not come up with a well designed fix yet. Maybe updating representation/as-response to fall-back to a default from :available-media-types but I’m not sure.

benzap08:02:03

I made a small modification to your code to hold onto the already present Accept header, seems to be working

benzap08:02:51

This sure isn't a well-designed fix, but it seems to be doing the trick lol

benzap09:02:18

Regardless of that, everything else in liberator is pretty amazing, I don't think I could have thrown together a restful api this quickly

ordnungswidrig09:02:05

Thanks! I really enjoy if people’s productivity increases.