I'm interested in using Fauna from browser from pure JS in read-only mode. Either official documentation lacks understandable information for this case or I can't figure it out. Please help me to understand.
I'm trying to run such query:
Map(Paginate(Documents(Collection('spells'))), Lambda('x', Get(Var('x'))));
Running this query from the shell gives me the result.
I want to push this query to JavaScript variable. But I don't understand what to do. Here is my code:
var client = new faunadb.Client({
secret: '320438826900127936',
keepAlive: false,
domain: 'db.eu.fauna.com',
// NOTE: Use the correct domain for your database's Region Group.
port: 443,
scheme: 'https',
});
var helper = client.paginate(
q.Match(
q.Index('spells'),
'101'
)
)
paginate.then(function(response) {
console.log(response.ref) // Would log the ref to console.
})
Please help me to get output from DB using pure JavaScript.
Using the JavaScript driver, all of the FQL functions are in
faunadb.querynamespace. Typically, developers would do this at the top of their scripts:After that, the FQL functions can be access using the
qobject. For example:q.Add(1, 2).Otherwise, you can use destructuring to import FQL functions into the script's namespace, like so:
and then you can call the FQL functions "directly", e.g.
Add(1, 2).If you use destructuring, be sure to import all of the FQL functions that you intend to use in your queries. Not all FQL functions can be imported "as-is", since some of their names would collide with built-in JavaScript names, such as
Function. For those, you have to assign them directly:And then use the local name that you specified (
FaunaFunctionin this case) when composing queries.Either way, the query itself isn't sent to Fauna until the
client.query(), or in your case,client.paginate(), function is called.That means that you can assign the FQL function calls to JavaScript variables. With the desired query, that could look like this:
Then you can do this:
You can use the
client.paginateif you are only performing pagination. Your desired query callsMap, so theclient.paginationhelper gets in your way. My example usesclient.query.Note that when you configure your client connection object, you don't need to specify the
portandschemeoptions; you're using the default values already. And you likely shouldn't change thekeepAliveoption unless your workflow specifically requires it.Plus, I see that you didn't include an actual secret in your example, which is a good thing: if you did include an actual secret, anyone with that secret could access your database just like you can.
If you want to see a complete (but simple) Fauna-based application that runs in a web page, see: https://github.com/fauna-labs/todo-vanillajs