Fork me on GitHub
#clojurescript
<
2020-08-21
>
zach23:08:10

Hi! I was wondering if there was a recommended way, when writing a node-targeted clojurescript app, to set the results of a json fetch to a variable? I have a static page generator written in clojure, that pulls in weather data from https://wttr.in and uses it to adjust the page in various ways. In clojure, I used clj-http.client and it was as simple as:

(def weather-info (:weather (parse-string (:body (client/get WTTR-JSON)) true)))
I am trying the same in clojurescript and getting stuck. the above library won't work, I tried cljs-http...but I think it is meant for the browser. Same with js/fetch , which is mentioned in the clojurescript docs. I'm trying to do it now using the npm module node-fetch but having a super hard time wrapping my head around translating the promise format of node-fetch into clojure. If anyone has done this, i'd be super happy to know what works for you! Thank you!

lilactown23:08:36

@webmaster601 unlike in Clojure, in CLJS you can’t typically block execution while doing a network request. What you can do is use something like node-fetch or some other nodejs lib to do the network request, and it will use either a promise or callback to signal when the request is complete. In the callback, you can then continue the rest of the static site generation

lilactown23:08:40

It will probably require some significant restructuring of your program if it’s built with the assumption that you can just refer to the weather data in a global variable

zach23:08:11

ah, that makes sense. So basically (pseudocode)

(-> (fetch WTTR_URL)
    (.then #(create-page %)))

zach23:08:33

(where create-page takes weatherinfo as an argument and uses it to run through all the page generation?

zach23:08:38

I think this is the other area where i'm a bit stuck, which is the transposing of code...in JS, that function would be something like:

fetch(WTTR_URL)
.then(res => res.json())
.then(json => createPage(json))
what would the res.json() portion look like in clojure? and would it be using the (.then #(some-function %) format i used above?

lilactown23:08:03

Yeah. I’m on mobile but calling methods is basically (.method object)