Calling a ".done" JS callback - clojurescript

I'm having some trouble with wrapping a JS library because I can't get a .done callback to work correctly. In JavaScript the code would look like this:
db.values("inventory").done(function(item) {
console.log(item);
});
So I tried a couple (very dirty) ClojureScript methods to translate this:
(defn log []
(console/log "working?"))
(defn stock []
(#(.done % log) (.values db "inventory")))
and
(defn stock []
(js* "db.values('inventory').done(function(item) {
console.log(item);
})"))
but neither of these worked. The error message is always something like: db.values(...).done is not a function
Are there any protocol extensions (or anything else) that could be used here to cover the JS callback? Otherwise, can goog.async.Deferred somehow intercept the callback again?

maybe this helps you!
I've done from node but it must work from browser with a little details
First for the demo code I've prepared a mock js lib to simulate yours (my_api.js)
This is my_api.js
console.log("my_api.js");
var db={};
db.item="";
db.values=function(_string_){
db.item="loadign_"+_string_;
return this;
};
db.done=function(_fn_){
_fn_(db.item);
};
var api={hello:"ey ", db:db};
module.exports=api;
// your pretended chain calls
// db.values("inventory").done(function(item) {
// console.log(item);
// });
And from clojurescript code ...
(ns cljs-demo.hello)
(defn example_callback []
(let [my-api (js/require "./my_api") ; the api.js lib used for this example
db (aget my-api "db") ; this is your db object
my_fn (fn [item] ;this is your callback function
(println "printing from clojurescript" item)
)
]
(do
(-> db (.values "inventory") (.done my_fn)) ;; calling your js in a similar way you want in js
;; or
(.done (.values db "inventory_bis") my_fn) ;; calling nested form in the standar lisp manner
)
)
)
(set! *main-cli-fn* example_callback) ;default node function
And from console (node.js)
node your_output_node.js
And you'll obtain
printing from clojurescript loadign_inventory
printing from clojurescript loadign_inventory_bis
Good Luck,
Juan

Related

Clojurescript advanced compilation unreachable-code

I have just added a new library(https://github.com/ptaoussanis/tempura/blob/master/README.md ) to my Clojurescript project.
WARNING: /matter/titan/source/titan-ui/out/taoensso/tempura/impl.js:96: WARNING - unreachable code}catch (e20422){if((e20422 instanceof Error)){
I also get this error :
Use of undeclared Var goog.structs/Map
(def ^:private coerce-xhr-params "Returns [<uri> <?data>]"
(let [url-encode
(fn url-encode
([params]
(when (seq params)
(-> params clj->js gstructs/Map. gquery-data/createFromMap .toString)))
^---
([uri params]
(let [qstr (url-encode params)
uri-with-query (if (str/blank? qstr) uri (str uri "?" qstr))]
[uri-with-query nil])))
Do I need to write an 'extern' for this? What does that look like?
It's hard to tell from your code and question details, but I assume you're having trouble with library call in advanced compilation mode.
The modern simple way is to skip externs thing altogether and just write calls/gets not in interop form, but by using https://github.com/binaryage/cljs-oops library.
You won't have to do anything else then - all your code will survive advanced compilation by default, no externs needed!
e.g. (.-nativeProp obj) would look like (oget obj "nativeProp"), and ocall is used for function calls correspondingly.

React HOC wrapping with Clojurescript and Reagent

I'm trying re-use the components from react-google-maps and implement the simple map example from the doc: https://tomchentw.github.io/react-google-maps/basics/simple-map
However, I'm a blocked by the withGoogleMap Higher-Order Component (HOC) that wraps the GoogleMap component. I have tried to adapt the classes with Reagent and use them as follow:
(def GoogleMap (adapt-react-class js/ReactGoogleMaps.GoogleMap))
(def withGoogleMap (adapt-react-class js/ReactGoogleMaps.withGoogleMap))
(defn Map [props]
[withGoogleMap
[GoogleMap props]])
in lieu of the following Javascript:
const Map = withGoogleMap(props => (
<GoogleMap
{... props}
>
</GoogleMap>
));
Without success. (I get the following error withGoogleMap(...): A valid React element (or null) must be returned. You may have returned undefined, an array or some other invalid object.).
The withGoogleMap HOC is a function that should be called with the wrapped component. To implement the simple map example, you also need to provide props to the GoogleMap component to be wrapped. This can be achieved by adapting the component to reagent with adapt-react-class, implementing the CLJS component, and "converting back" with reactify-component before calling the HOC.
(ns simple-map.views
(:require [reagent.core :refer [adapt-react-class
create-element
reactify-component]]
react-google-maps))
(defn my-google-map []
(let [google-map (adapt-react-class react-google-maps/GoogleMap)]
[google-map {:defaultZoom 18
:defaultCenter {:lat 61.4481532
:lng 23.8608644}}]))
(defn MyMap [props]
(let [m (-> my-google-map
reactify-component
react-google-maps/withGoogleMap
adapt-react-class)]
[m props]))
(defn main-panel []
(let [container-element (create-element "div" #js{:style (clj->js {:height "768px" :width "1024px"})})
map-element (create-element "div" #js{:style (clj->js {:height "768px" :width "1024px"})})]
(fn []
[:div
[MyMap {:containerElement container-element
:mapElement map-element}]])))
Note that I am using the experimental :npm-deps support to require react-google-maps.

Why do js functions fail when I assign them to a local variable?

In clojurescript 1.9.89 and Chrome 50.0.2661.102, I can create a log statement like:
(js/console.log "works")
But I can't create one like:
(def brokenlog js/console.log)
(brokenlog "but not here")
--> #object[TypeError TypeError: Illegal invocation]
When I try to compare these approaches by printing the value of my own brokenlog function, it looks just like the "real one" -- that is, both brokenlog and js/console.log evaluate for me as:
#object[log "function log() { [native code] }"]
Similarly, I see this behavior with:
cljs.user=> (js/document.querySelector "body")
#object[HTMLBodyElement [object HTMLBodyElement]]
cljs.user=> (def l js/document.querySelector)
#'cljs.user/l
cljs.user=> (l "body")
#object[TypeError TypeError: Illegal invocation]
nil
Upgrading to Chrome 52 fixes the console.log behavior, but not the document.querySelector behavior.
So I have two questions:
1. What am I missing
2. Where are the official docs I should be reading that would explain it?
Thanks!
Which browser and clojurescript version you are using?
the following code should work on your browser if it display nil into box.
.as-console-wrapper .as-console {
display: none;
}
<pre><code class="language-klipse">
(js/console.log "Work!")
(def brokenlog js/console.log)
(brokenlog "Work again!")
; two line should be seen in your browser log
</code></pre>
<script>
window.klipse_settings = {
selector: '.language-klipse', // css selector for the html elements you want to klipsify
};
</script>
<script src="http://app.klipse.tech/plugin/js/klipse_plugin.js?"></script>
<link href="http://app.klipse.tech/css/codemirror.css" rel="stylesheet"/>
EDIT
Here is the clojurescript
(ns hello-world.core)
(def mylog js/console.log)
(mylog "Hello")
compiled to javascript
hello_world.core.mylog = console.log;
hello_world.core.mylog.call(null,"Hello");
console.log.call(null, ....) trigger the chrome bug, console.log expecting this is the console object. It should be fixed as mentioned in the issue log https://bugs.chromium.org/p/chromium/issues/detail?id=167911.

How to extract the results of Http Requests in Elm

Using Elm's html package it is possible to make http requests:
https://api.github.com/users/nytimes/repos
These are all the New York Times repos on Github. Basically there are two items I'd want from the Github response, the id and name
[ { "id": 5803599, "name": "backbone.stickit" , ... },
{ "id": 21172032, "name": "collectd-rabbitmq" , ... },
{ "id": 698445, "name": "document-viewer" , ... }, ... ]
The Elm type for Http.get requires a Json Decoder object
> Http.get
<function> : Json.Decode.Decoder a -> String -> Task.Task Http.Error a
I don't know how to open lists yet. So I put the decoder Json.Decode.string and at least the types matched, but I had no idea what to do with the task object.
> tsk = Http.get (Json.Decode.list Json.Decode.string) url
{ tag = "AndThen", task = { tag = "Catch", task = { tag = "Async", asyncFunction = <function> }, callback = <function> }, callback = <function> }
: Task.Task Http.Error (List String)
> Task.toResult tsk
{ tag = "Catch", task = { tag = "AndThen", task = { tag = "AndThen", task = { tag = "Catch", task = { tag = "Async", asyncFunction = <function> }, callback = <function> }, callback = <function> }, callback = <function> }, callback = <function> }
: Task.Task a (Result.Result Http.Error (List String))
I just want an Elm object of the repo names so I can display in some div elements, but I can't even get the data out.
Can someone slowly walk me through how to write the decoder and how to get the data out with Elm?
Update for Elm 0.17:
I have updated the complete gist of this answer to work with Elm 0.17. You can see the full source code here. It will run on http://elm-lang.org/try.
A number of language and API changes were made in 0.17 that make some of the following recommendations obsolete. You can read about the 0.17 upgrade plan here.
I will leave the original answer for 0.16 untouched below, but you can compare the final gists to see a list of what has changed. I believe the newer 0.17 version is cleaner and easier to understand.
Original Answer for Elm 0.16:
It looks like you're using the Elm REPL. As noted here, you're not going to be able to execute tasks in the REPL. We'll get to more on why in a bit. Instead, let's create an actual Elm project.
I'm assuming you've downloaded the standard Elm tools.
You'll first need to create a project folder and open it up in a terminal.
A common way to get started on an Elm project is to use the StartApp. Let's use that as a starting point. You first need to use the Elm package manager command line tool to install the required packages. Run the following in a terminal in your project root:
elm package install -y evancz/elm-html
elm package install -y evancz/elm-effects
elm package install -y evancz/elm-http
elm package install -y evancz/start-app
Now, create a file at the project root called Main.elm. Here is some boilerplate StartApp code to get you started. I won't go into explaining the details here since this question is specifically about Tasks. You can learn more by going through the Elm Architecture Tutorial. For now, copy this into Main.elm.
import Html exposing (..)
import Html.Events exposing (..)
import Html.Attributes exposing (..)
import Html.Attributes exposing (..)
import Http
import StartApp
import Task exposing (Task)
import Effects exposing (Effects, Never)
import Json.Decode as Json exposing ((:=))
type Action
= NoOp
type alias Model =
{ message : String }
app = StartApp.start
{ init = init
, update = update
, view = view
, inputs = [ ]
}
main = app.html
port tasks : Signal (Task.Task Effects.Never ())
port tasks = app.tasks
init =
({ message = "Hello, Elm!" }, Effects.none)
update action model =
case action of
NoOp ->
(model, Effects.none)
view : Signal.Address Action -> Model -> Html
view address model =
div []
[ div [] [ text model.message ]
]
You can now run this code using elm-reactor. Go to the terminal in your project folder and enter
elm reactor
This will run a web server on port 8000 by default, and you can pull up http://localhost:8000 in your browser, then navigate to Main.elm to see the "Hello, Elm" example.
The end goal here is to create a button which, when clicked, pulls in the list of nytimes repositories and lists the IDs and names of each. Let's first create that button. We'll do so by using the standard html generation functions. Update the view function with something like this:
view address model =
div []
[ div [] [ text model.message ]
, button [] [ text "Click to load nytimes repositories" ]
]
On its own, the button click does nothing. We need to create an Action that is then handled by the update function. The action the button is initiating is to fetch data from the Github endpoint. Action now becomes:
type Action
= NoOp
| FetchData
And we can now stub out the handling of this action in the update function like so. For now, let's change the message to show that the button click was handled:
update action model =
case action of
NoOp ->
(model, Effects.none)
FetchData ->
({ model | message = "Initiating data fetch!" }, Effects.none)
Lastly, we have to cause button clicks to trigger that new action. This is done using the onClick function, which generates a click event handler for that button. The button html generation line now looks like this:
button [ onClick address FetchData ] [ text "Click to load nytimes repositories" ]
Great! Now the message should be updated when you click it. Let's move onto Tasks.
As I mentioned earlier, the REPL does not (yet) support the invoking of tasks. This may seem counterintuitive if you're coming from an imperative language like Javascript, where when you write code that says "go fetch data from this url," it immediately creates an HTTP request. In a purely functional language like Elm, you do things a little differently. When you create a Task in Elm, you're really just indicating your intentions, creating a sort of "package" that you can hand off to the runtime in order to do something that causes side effects; in this case, contact the outside world and pull data down from a URL.
Let's go ahead and create a task that fetches the data from the url. First, we're going to need a type inside Elm to represent the shape of the data we care about. You indicated that you just wanted the id and name fields.
type alias RepoInfo =
{ id : Int
, name : String
}
As a note about type construction inside Elm, let's stop for a minute and talk about how we create RepoInfo instances. Since there are two fields, you can construct a RepoInfo in one of two ways. The following two statements are equivalent:
-- This creates a record using record syntax construction
{ id = 123, name = "example" }
-- This creates an equivalent record using RepoInfo as a constructor with two args
RepoInfo 123 "example"
That second was of constructing the instance will become more important when we talk about Json decoding.
Let's also add a list of these to the model. We'll have to change the init function as well to start off with an empty list.
type alias Model =
{ message : String
, repos : List RepoInfo
}
init =
let
model =
{ message = "Hello, Elm!"
, repos = []
}
in
(model, Effects.none)
Since the data from the URL comes back in JSON format, We'll need a Json Decoder to translate the raw JSON into our type-safe Elm class. Create the following decoder.
repoInfoDecoder : Json.Decoder RepoInfo
repoInfoDecoder =
Json.object2
RepoInfo
("id" := Json.int)
("name" := Json.string)
Let's pick that apart. A decoder is what maps the raw JSON to the shape of the type to which we're mapping. In this case, our type is a simple record alias with two fields. Remember that I mentioned a few steps ago that we can create a RepoInfo instance by using RepoInfo as a function that takes two parameters? That's why we're using Json.object2 to create the decoder. The first arg to object is a function that takes two arguments itself, and that's why we're passing in RepoInfo. It is equivalent to a function with arity two.
The remaining arguments spell out the shape of the type. Since our RepoInfo model lists id first and name second, that's the order in which the decoder expects the arguments to be.
We'll need another decoder to decode a list of RepoInfo instances.
repoInfoListDecoder : Json.Decoder (List RepoInfo)
repoInfoListDecoder =
Json.list repoInfoDecoder
Now that we have a model and decoder, we can create a function that returns the task for fetching the data. Remember, this isn't actually fetching any data, it's merely creating a function which we can hand off to the runtime later.
fetchData : Task Http.Error (List RepoInfo)
fetchData =
Http.get repoInfoListDecoder "https://api.github.com/users/nytimes/repos"
There are a number of ways of handling the variety of errors that can occur. Let's choose Task.toResult, which maps the result of the request to a Result type. It will make things easier on us in a bit, and is sufficient for this example. Let's change that fetchData signature to this:
fetchData : Task x (Result Http.Error (List RepoInfo))
fetchData =
Http.get repoInfoListDecoder "https://api.github.com/users/nytimes/repos"
|> Task.toResult
Note that I'm using x in my type annotation for the error value of Task. That's just because, by mapping to a Result, I'll never have to care about an error from the task.
Now, we're going to need some actions to handle the two possible results: An HTTP error or a successful result. Update Action with this:
type Action
= NoOp
| FetchData
| ErrorOccurred String
| DataFetched (List RepoInfo)
Your update function should now set those values on the model.
update action model =
case action of
NoOp ->
(model, Effects.none)
FetchData ->
({ model | message = "Initiating data fetch!" }, Effects.none)
ErrorOccurred errorMessage ->
({ model | message = "Oops! An error occurred: " ++ errorMessage }, Effects.none)
DataFetched repos ->
({ model | repos = repos, message = "The data has been fetched!" }, Effects.none)
Now, we need a way to map the Result task to one of these new actions. Since I don't want to get bogged down in error handling, I'm just going to use toString to change the error object into a string for debugging purposes
httpResultToAction : Result Http.Error (List RepoInfo) -> Action
httpResultToAction result =
case result of
Ok repos ->
DataFetched repos
Err err ->
ErrorOccurred (toString err)
That gives us a way to map a never-failing task to an Action. However, StartApp deals with Effects, which is a thin layer over Tasks (as well as a few other things). We'll need one more piece before we can tie it all together, and that's a way to map the never-failing HTTP task to an Effects of our type Action.
fetchDataAsEffects : Effects Action
fetchDataAsEffects =
fetchData
|> Task.map httpResultToAction
|> Effects.task
You may have noticed I called this thing, "never failing." That was confusing to me at first so let me try to explain. When we create a task, we're guaranteed a result, but it a success or failure. In order to make Elm apps as robust as possible, we in essence remove the possibility of failure (by which I mainly mean, an unhandled Javascript exception), by explicitly handling every case. That's why we've gone through the trouble of mapping first to a Result and then to our Action, which explicitly handles error messages. To say it never fails is not to say that HTTP problems can't happen, it's to say that we're handling every possible outcome, and errors are mapped to "successes" by mapping them to a valid action.
Before our final step, let's make sure our view can show the list of repositories.
view : Signal.Address Action -> Model -> Html
view address model =
let
showRepo repo =
li []
[ text ("Repository ID: " ++ (toString repo.id) ++ "; ")
, text ("Repository Name: " ++ repo.name)
]
in
div []
[ div [] [ text model.message ]
, button [ onClick address FetchData ] [ text "Click to load nytimes repositories" ]
, ul [] (List.map showRepo model.repos)
]
Lastly, the piece that ties this all together is to make the FetchData case of our update function return the Effect which initiates our task. Update the case statement like this:
FetchData ->
({ model | message = "Initiating data fetch!" }, fetchDataAsEffects)
That's it! You can now run elm reactor and click the button to fetch the list of repositories. If you want to test out the error handling, you can just mangle the URL for the Http.get request to see what happens.
I've posted the entire working example of this as a gist. If you don't want to run it locally, you can see the final result by pasting that code into http://elm-lang.org/try.
I've tried to be very explicit and concise about each step along the way. In a typical Elm app, a lot of these steps will be condensed down to a few lines, and more idiomatic shorthand will be used. I've tried to spare you those hurdles by making things as small and explicit as possible. I hope this helps!

Using hunchentoot to parse post request sent by model.save() in Backbone.js

I am a javascript/web application newbie and trying to implement my first web application using hunchentoot and backbone.js. The first thing I was experimenting is to understand how model.fetch() and model.save() work.
It seems to me that model.fetch() fires a "GET" request and model.save() fires a "POST" request instead. Therefore, I wrote a easy-handler in hunchentoot as below:
(hunchentoot:define-easy-handler (dataset-handler :uri "/dataset") ()
(setf (hunchentoot:content-type*) "text/html")
;; get the request type, canbe :get or :post
(let ((request-type (hunchentoot:request-method hunchentoot:*request*)))
(cond ((eq request-type :get)
(dataset-update)
;; return the json boject constructed by jsown
(jsown:to-json (list :obj
(cons "length" *dataset-size*)
(cons "folder" *dataset-folder*)
(cons "list" *dataset-list*))))
((eq request-type :post)
;; have no idea on what to do here
....))))
This is designed to handle the fetch/save of a model whose corresponding url is "/dataset". The fetch works fine, but I got really confused by the save(). I saw the "post" request fired and handled by the easy-handler, but the request seems to have only a meaningful header, I cannot find the actual json object hidden in the request. So my question is
How can I get the json object out of the post request fired by model.save(), so that later json library (e.g., jsown) can be used to parse it?
What should hunchentoot reply in order to let the client know that the "save" is successful?
I tried "post-parameters" function in hunchentoot and it returns nil, and didn't see many people using hunchentoot+backbone.js by googling. It is also helpful if you can direct me to some articles/blog posts that help understanding how the backbone.js save() works.
Thank you very much for your patience!
Thanks to wvxvw's comments, I found the solution to this question. The json object can be retrieved by calling hunchentoot:raw-post-data. To be more detailed, we first call (hunchentoot:raw-post-data :force-text t) to get the post data as a string, and then feed it to jsown:parse. A complete easy-handler is shown below:
(hunchentoot:define-easy-handler (some-handler :uri "/some") ()
(setf (hunchentoot:content-type*) "text/html")
(let ((request-type (hunchentoot:request-method hunchentoot:*request*)))
(cond ((eq request-type :get) ... );; handle get request
((eq request-type :post)
(let* ((data-string (hunchentoot:raw-post-data :force-text t))
(json-obj (jsown:parse data-string))) ;; use jsown to parse the string
.... ;; play with json-obj
data-string))))) ;; return the original post data string, so that the save() in backbone.js will be notified about the success.
Hope this helps others who have the same confusion.