Fork me on GitHub
#nbb
<
2023-10-13
>
sher11:10:32

Docs say that nbb.core/slurp returns a Promise. What is the correct way to await for the resolved value? (print (await (slurp "file.txt"))) is still returning a promise #object[Promise [object Promise]]. Seems l am missing something

borkdude11:10:39

await in nbb only works on top level values. in the REPL you can do

(await (slurp "file.txt"))

borkdude11:10:08

or

(def x (await (slurp "file.txt"))
also works, which binds the contents of the file to x

borkdude11:10:20

and then use println on x

sher11:10:38

Oh I see.

borkdude11:10:50

but you might as well use (require '["fs" :as fs]) and (fs/readFileSync "file.txt" "UTF-8")

upvote 1
sher11:10:16

Great, thank you.

sher14:10:07

Trying to make this function more readable, could someone suggest a better alternative to nested lets/ifs. Something like an early escape/return pattern? https://github.com/sher/nbb/blob/extend-fastify/examples/fastify/src/fastify_nbb/plugins/auth.cljs#L28-L41

(defn pre-handler
  [req _ done]
  (if (pathname-whitelisted? (j/get req :url))
    :default
    (let [cookies (j/get req :cookies)]
      (if-let [signed-cookie (j/get cookies :token)]
        (let [unsigned-cookie (.unsignCookie req signed-cookie)]
          (if (j/get unsigned-cookie :valid)
            (if-let [token (jwt-verify-sync (j/get unsigned-cookie :value))]
              (println "--->>>" token)
              (throw (js/Error "ERR_UNAUTHORIZED")))
            (throw (js/Error "ERR_UNAUTHORIZED"))))
        (throw (js/Error "ERR_UNAUTHORIZED")))))
  (done))

borkdude14:10:23

This is probably how it should look, unless you use a more complicated macro like better-cond

sher14:10:27

Thank you, guess it takes getting used to.

Bob B14:10:06

if j has get-in, you could maybe eliminate one layer of nesting with (get-in req [:cookies :token]) - at least based on a quick skim, it doesn't look like cookies is being used elsewhere

👍 2