clj-rethinkdb icon indicating copy to clipboard operation
clj-rethinkdb copied to clipboard

Add ClojureScript query building examples

Open arichiardi opened this issue 9 years ago • 2 comments
trafficstars

Hello folks!

I need just some minimal example to get going. I am willing to create a wiki page if I get some hint on where to start, I saw query and query-builder namespaces but I was not able (not tried super hard I have to say) to make them work together from cljs files.

I understood that I then should send the query to the server and execute from there. Is that right?

arichiardi avatar Jul 04 '16 01:07 arichiardi

Hey! Here's how we do it:

  1. Generate queries in cljs
  2. Send them to the server (we use Transit and Sente)
  3. Validate the queries are safe
  4. Other security stuff (check username, e.t.c.)
  5. Run them asynchronously
  6. Reply back to the client that we're running their queries
  7. Return results asynchronously

Generating the queries happens the same as you would in Clojure, e.g.

(ns my-ns [rethinkdb.query :as r :include-macros true])

(defn users-table []
  (-> (r/db "myapp")
      (r/table "users")))

When users-table is executed, it will return data like this:

{:rethinkdb.query-builder/term :TABLE,
 :rethinkdb.query-builder/args [{:rethinkdb.query-builder/term :DB,
                                 :rethinkdb.query-builder/args ["myapp"],
                                 :rethinkdb.query-builder/optargs nil}
                                "users"],
 :rethinkdb.query-builder/optargs nil}

That's plain old Clojure data you can send via Transit. Then when you get that data on the other end, just call (r/run query-from-cljs conn) in your Clojure code, or the equivalent async call.

The very obvious problem here is accepting untrusted db queries. I don't have a great fully general solution to this. As I was writing this comment, I remembered https://github.com/zubairq/BlocklyBuilder#is-it-secure-to-have-sql-in-the-ui-code. I haven't vetted it, but that seems like it might be an ok way to do it???

danielcompton avatar Jul 05 '16 04:07 danielcompton

Thanks for the detailed answer, I also read about privacy concerns and I guess encripting is fine, even if JavaScript randomness leaves something to be desired ... probably coupled with authorization of the endpoint as well... I might write a short example app to see how it feels before using it.

arichiardi avatar Jul 05 '16 04:07 arichiardi