GithubHelp home page GithubHelp logo

fauna / faunadb-js Goto Github PK

View Code? Open in Web Editor NEW
702.0 42.0 76.0 31.87 MB

Javascript driver for Fauna v4

Home Page: https://docs.fauna.com/fauna/v4/

License: Other

JavaScript 99.34% Shell 0.66%
drivers faunadb driver client clients fauna javascript database

faunadb-js's Introduction

Official JavaScript driver for Fauna v4

CircleCI Npm Version License semantic-release

Caution

This driver is not compatible with Fauna v10, the latest version.

For new development, use the official Fauna v10 driver: https://github.com/fauna/fauna-js.

The official JavaScript driver for Fauna v4.

View reference JSDocs here.

See the FaunaDB Documentation and Tutorials for guides and a complete database API reference.

Supported Runtimes

This Driver supports and is tested on:

Using the Client

Installation

Node.js

npm install --save faunadb

or

yarn add faunadb

Browsers

Via CDN:

<script src="//cdn.jsdelivr.net/npm/faunadb@latest/dist/faunadb.js"></script>

The minified version of the driver can also be used via CDN:

<script src="//cdn.jsdelivr.net/npm/faunadb@latest/dist/faunadb-min.js"></script>

Use

The tutorials in the FaunaDB documentation contain other driver-specific examples.

Connecting from the browser

To get up and running quickly, below is a full example for connecting from the browser. Replace <your_key_here> with a database secret. You can get that by visiting your FaunaDB Dashboard, creating a new database, clicking on "Security" in the sidebar on the left, and then clicking "New Key". To learn more about keys, see FaunaDB Key System.

<html>
  <head>
  </head>
<body>
  <h1>Test</h1>
</body>
<script src="https://cdn.jsdelivr.net/npm/faunadb@latest/dist/faunadb.js"></script>
<script type="text/javascript">
  var faunadb = window.faunadb
  var q = faunadb.query
  var client = new faunadb.Client({
    secret: 'your_key_here',
    domain: 'db.fauna.com',
    scheme: 'https',
  })
  client.query(
    q.ToDate('2018-06-06')
  )
  .then(function (res) { console.log('Result:', res) })
  .catch(function (err) { console.log('Error:', err) })
</script>
</html>

Requiring the Driver

var faunadb = require('faunadb'),
  q = faunadb.query

This is the recommended require stanza. The faunadb.query module contains all of the functions to create FaunaDB Query expressions.

Instantiating a Client and Issuing Queries

var client = new faunadb.Client({ secret: 'YOUR_FAUNADB_SECRET' })

Once the client has been instantiated, it can be used to issue queries. For example, to create an document in an existing collection named test with the data: { testField: 'testValue' }:

var createP = client.query(
  q.Create(q.Collection('test'), { data: { testField: 'testValue' } })
)

All methods on faunadb.Client return ES6 Promises. So, if we wanted to handle the Promise to access the Ref of the newly created document:

createP.then(function(response) {
  console.log(response.ref) // Would log the ref to console.
})

response is a JSON object containing the FaunaDB response. See the JSDocs for faunadb.Client.

The metrics option is used during instantiation to create a client that also returns usage information about the queries issued to FaunaDB.

let client = new faunadb.Client({
  secret: 'YOUR_FAUNADB_SECRET',
  metrics: true
})

Querying and Returning the metrics of your queries

The response object is shaped differently for clients when calling queryWithMetrics; it includes the value of the response along with a metrics field giving data on ops, time, and transaction retires consumed by your query:

{
  value: { ... }, // structured response body
  metrics: {
    x-compute-ops: XX,
    x-byte-read-ops: XX,
    x-byte-write-ops: XX,
    x-query-time: XX,
    x-txn-retries: XX
  } // usage data
}

Metrics returned in the response will be of number data type.

Pagination Helpers

This driver contains helpers to provide a simpler API for consuming paged responses from FaunaDB. See the Paginate function reference for a description of paged responses.

Using the helper to page over sets lets the driver handle cursoring and pagination state. For example, client.paginate:

var helper = client.paginate(q.Match(q.Index('test_index'), 'example-term'))

The return value, helper, is an instance of PageHelper. The each method will execute a callback function on each consumed page.

helper.each(function(page) {
  console.log(page) // Will log the page's contents, for example: [ Ref("collections/test/1234"), ... ]
})

Note that each returns a Promise<void> that is fulfilled on the completion of pagination.

The pagination can be transformed server-side via the FaunaDB query language via the map and filter functions.

For example, to retrieve the matched documents:

helper
  .map(function(ref) {
    return q.Get(ref)
  })
  .each(function(page) {
    console.log(page) // Will now log the retrieved documents.
  })

See the JSDocs for more information on the pagination helper.

Timeouts

The client can be configured to handle timeouts in two different ways:

  1. Add a timeout field to the options block when instantiating the client
  2. By setting a queryTimeout on the client (or passing the value to the client's .query() method directly)

The first option (i.e. timeout) represents a HTTP timeout on the client side. Defined in seconds, the client will wait the specified period before timing out if it has yet to receive a response.

const client = new faunadb.Client({
  secret: 'YOUR_FAUNADB_SECRET',
  timeout: 100,
})

On the other hand, using the client's queryTimeout dictates how long FaunaDB will process the request on the server before timing out if it hasn't finished running the operation. This can be done in two different ways:

// 1. Setting the value when instantiating a new client
const client = new faunadb.Client({
  queryTimeout: 2000,
  secret: 'YOUR_FAUNADB_SECRET',
})

// 2. Specifying the value per-query
var data = client.query(q.Paginate(q.Collections()), {
  queryTimeout: 100,
})

Note: When passing a queryTimeout value to client.query() as part of the options object, it will take precendence over any value set on the client when instantiating it.

Per-query options

Some options can be provided on a per-query basis:

secret
var createP = client.query(
  q.Create(q.Collection('test'), { data: { testField: 'testValue' } }),
  { secret: 'YOUR_FAUNADB_SECRET' }
)
var helper = client.paginate(
  q.Match(q.Index('test_index'), 'example-term'),
  null,
  {
    secret: 'YOUR_FAUNADB_SECRET',
  }
)
queryTimeout
var data = client.query(q.Paginate(q.Collections()), {
  queryTimeout: 100,
})
traceparent

A W3C-compliant identifier for enabling distributed tracing across different vendors. If not provided, one is automatically generated server-side and attached to the query. Customer's should inspect the returned traceresponse to determine if a new traceparent has been created, and use that instead. See Trace Context spec for more details.

var data = client.query(q.Paginate(q.Collections()), {
  traceparent: "00-c91308c112be8448dd34dc6191567fa0-b7ad6b7169203331-01",
})
tags

Allows for associating user-provided tags with a query.

var data = client.query(q.Paginate(q.Collections()), {
  tags: { key1: "value1", key2: "value2" },
})

Both tags and their associated values, must be strings. The only allowable characters are alphanumeric values as well as an underscope (_). Max length for keys is 40 characters. Max length for values is 60 characters.

Custom Fetch

To use a custom fetch() you just have to specify it in the configuration and make it compatible with the standard Web API Specification of the Fetch API.

const customFetch = require('./customFetch')
const client = new faunadb.Client({
  secret: 'YOUR_FAUNADB_SECRET',
  fetch: customFetch,
})

HTTP/2 Session Idle Time (Node.js only)

When running on the Node.js platform, the Fauna client uses HTTP/2 multiplexing to reuse the same session for many simultaneous requests. After all open requests have been resolved, the client will keep the session open for a period of time (500ms by default) to be reused for any new requests.

The http2SessionIdleTime parameter may be used to control how long the HTTP/2 session remains open while the query connection is idle. To save on the overhead of closing and re-opening the session, set http2SessionIdleTime to a longer time. The default value is 500ms and the maximum value is 5000ms.

Note that http2SessionIdleTime has no effect on a stream connection: a stream is a long-lived connection that is intended to be held open indefinitely.

While an HTTP/2 session is alive, the client holds the Node.js event loop open; this prevents the process from terminating. Call Client#close to manually close the session and allow the process to terminate. This is particularly important if http2SessionIdleTime is long:

// sample.js (run it with "node sample.js" command)
const { Client, query: Q } = require('faunadb')

async function main() {
  const client = new Client({
    secret: 'YOUR_FAUNADB_SECRET',
    http2SessionIdleTime: 1000, // Must be a non-negative integer
  })
  const output = await client.query(Q.Add(1, 1))

  console.log(output)

  client.close()
}

main().catch(console.error)

Known issues

Using with Cloudflare Workers

Cloudflare Workers have neither XMLHttpRequest nor fetch in the global scope. Therefore, the cross-fetch package is unable to inject its own fetch() function, and throws an error. The fetch() function is injected via a closure, so the workaround would be to pass the fetch objects when initiating the FaunaDB client config. Cloudflare Workers also doesn't support the use of an AbortController, which terminates requests as well as streams. Here is a workaround:

const c = new faunadb.Client({
  secret: 'your secret',
  fetch: (url, params) => {
    const signal = params.signal
    delete params.signal
    const abortPromise = new Promise(resolve => {
      if (signal) {
        signal.onabort = resolve
      }
    })
    return Promise.race([abortPromise, fetch(url, params)])
  },
})

Client Development

Run yarn to install dependencies.

Code

This project includes no polyfills. Support for Internet Explorer 11 requires a Promise polyfill.

Testing

The driver tests need to connect to a FaunaDB so we recommend you setup one locally. The fast way is running a docker image like docker run --rm --name faunadb -p 8443:8443 fauna/faunadb.

After have the faunadb working on local you have to setup a set of env variables before run the tests. You can set them manually or use a .env file for this.

FAUNA_DOMAIN=localhost
FAUNA_SCHEME=http
FAUNA_PORT=8443
FAUNA_ROOT_KEY=secret
AUTH_0_URI=https://{TENANT}.auth0.com/
AUTH_0_TOKEN=auth0 token

Guide for Auth0

  • yarn test: This will run tests against the current version of Node.js. nvm is useful for managing multiple versions of Node.js for testing.

Each test run will create a new database, and will attempt to clean it up when done. If the tests are cancelled, the test database will not get cleaned up. Therefore it is recommended to use a FaunaDB key scoped to an empty parent database created for this purpose, rather than your account's root key. This will make cleanup of test databases as easy as removing the parent database.

See the FaunaDB Multi-tenancy Tutorial for more information about nested databases.

Alternatively, tests can be run via a Docker container with FAUNA_ROOT_KEY="your-cloud-secret" make docker-test (an alternate Alpine-based NodeJS image can be provided via RUNTIME_IMAGE).

Documentation

  • yarn doc will generate JSDoc documentation for the project.

Previewing upcoming functionality

If you want to preview unreleased features in your project, you can do so by installing this driver using one of the following methods.

1. Using a git URL

Normally, you would install the latest release of this package using npm install --save faunadb or yarn add faunadb. To access our latest features, you will need to define this dependency by using a git URL.

  1. Open your package.json file

  2. If you have already installed this driver, you should see the following in your list of dependencies. If not, add it.

"faunadb": "^2.14.1"
  1. Instead of using a version from the npm registry, we'll want to point our package.json to the main branch of our GitHub repo. To do that, change the ^2.4.1 to fauna/faunadb-js#main.
"faunadb": "fauna/faunadb-js#main"
  1. Update your node_modules by running npm install or yarn

2. Using npm pack

  1. Clone this repo to your local system
git clone https://github.com/fauna/faunadb-js.git
  1. Navigate to the cloned repo and open the package.json
cd faunadb-js
code package.json
  1. Change the version to be semantic. For example, 3.0.0-beta.

  2. Run npm pack. This creates a tarball at the root of your project directory which represents the image sent to the NPM registry when publishing.

  3. In another project, you can now install the beta from the local image you just created by running:

npm install /path/to/tarball

License

Copyright 2023 Fauna, Inc.

Licensed under the Mozilla Public License, Version 2.0 (the "License"); you may not use this software except in compliance with the License. You may obtain a copy of the License at

http://mozilla.org/MPL/2.0/

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

faunadb-js's People

Contributors

alvarofauna avatar andy-faunadb avatar artyom-kurnikov avatar ashfire908 avatar bitbckt avatar brunoquaresma avatar cleve-fauna avatar danieltodonnell avatar dependabot-preview[bot] avatar dependabot[bot] avatar eaceaser avatar ecwyne avatar elersong avatar erickpintor avatar fauna-ryan avatar faunaee avatar fireridlle avatar gahabeen avatar henryfauna avatar jfmiii avatar macnealefauna avatar marrony avatar n400 avatar parkhomenko avatar ptpaterson avatar rodrimaia avatar rts-rob avatar ryancharris avatar sprsquish avatar yesha-fauna avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

faunadb-js's Issues

Consider removing `dist` from the repo

We had to add this because a new version of npm was updating babel to the wrong version.
Once we're using the new babel we should be able to go back to compiling on install.

Add a ref helper to the query DSL

There may be a reason to not do this, but instantiating a ref object feels like a break in the flow when constructing a query.

client.query(query.get(query.ref("databases/foo"))) flows better than client.query(query.get(new object.Ref("databases/foo")))

Module not found: Error: Can't resolve 'http' in FaunaDB JavaScript Driver

I'm trying to use FaunaDB in an Ionic project, but a problem has arisen that I don't know how to solve.

I simply created a new project and installed the driver:

ionic start --type=angular my-app blank
npm i faunadb

Then, I instantiate FaunaDB.Cliente:

import * as FaunaDB from 'faunadb';
const client = new FaunaDB.Client({
  secret: environment.faunadb.secret,
  keepAlive: false,
});

Works well in development! But when I build for production, using this command:

ionic build --prod

And the following error happens:

ERROR in ../node_modules/faunadb/src/Client.js
Module not found: Error: Can't resolve 'http' in 'D:\Workspace\www\fanstore\workspace\node_modules\faunadb\src'
resolve 'http' in 'D:\Workspace\www\fanstore\workspace\node_modules\faunadb\src'
  Parsed request is a module
  using description file: D:\Workspace\www\fanstore\workspace\node_modules\faunadb\package.json (relative path: ./src)
    Field 'browser' doesn't contain a valid alias configuration
    resolve as module
      looking for modules in D:/Workspace/www/fanstore/workspace/my-app/
        using description file: D:\Workspace\www\fanstore\workspace\my-app\package.json (relative path: .)
          Field 'browser' doesn't contain a valid alias configuration
          using description file: D:\Workspace\www\fanstore\workspace\my-app\package.json (relative path: ./http)
            no extension
              Field 'browser' doesn't contain a valid alias configuration
              D:\Workspace\www\fanstore\workspace\my-app\http doesn't exist
            .ts
              Field 'browser' doesn't contain a valid alias configuration
              D:\Workspace\www\fanstore\workspace\my-app\http.ts doesn't exist
            .tsx
              Field 'browser' doesn't contain a valid alias configuration
              D:\Workspace\www\fanstore\workspace\my-app\http.tsx doesn't exist
            .mjs
              Field 'browser' doesn't contain a valid alias configuration
              D:\Workspace\www\fanstore\workspace\my-app\http.mjs doesn't exist
            .js
              Field 'browser' doesn't contain a valid alias configuration
              D:\Workspace\www\fanstore\workspace\my-app\http.js doesn't exist
            as directory
              D:\Workspace\www\fanstore\workspace\my-app\http doesn't exist
      D:\Workspace\www\fanstore\workspace\node_modules\faunadb\src\node_modules doesn't exist or is not a directory
      D:\Workspace\www\fanstore\workspace\node_modules\faunadb\node_modules doesn't exist or is not a directory
      D:\Workspace\www\fanstore\workspace\node_modules\node_modules doesn't exist or is not a directory
      D:\Workspace\www\fanstore\node_modules doesn't exist or is not a directory
      D:\Workspace\www\node_modules doesn't exist or is not a directory
      D:\Workspace\node_modules doesn't exist or is not a directory
      D:\node_modules doesn't exist or is not a directory
      looking for modules in D:\Workspace\www\fanstore\workspace\node_modules
        No description file found
        Field 'browser' doesn't contain a valid alias configuration
        No description file found
        no extension
          Field 'browser' doesn't contain a valid alias configuration
          D:\Workspace\www\fanstore\workspace\node_modules\http doesn't exist
        .ts
          Field 'browser' doesn't contain a valid alias configuration
          D:\Workspace\www\fanstore\workspace\node_modules\http.ts doesn't exist
        .tsx
          Field 'browser' doesn't contain a valid alias configuration
          D:\Workspace\www\fanstore\workspace\node_modules\http.tsx doesn't exist
        .mjs
          Field 'browser' doesn't contain a valid alias configuration
          D:\Workspace\www\fanstore\workspace\node_modules\http.mjs doesn't exist
        .js
          Field 'browser' doesn't contain a valid alias configuration
          D:\Workspace\www\fanstore\workspace\node_modules\http.js doesn't exist
        as directory
          D:\Workspace\www\fanstore\workspace\node_modules\http doesn't exist
[D:\Workspace\www\fanstore\workspace\my-app\http]
[D:\Workspace\www\fanstore\workspace\my-app\http.ts]
[D:\Workspace\www\fanstore\workspace\my-app\http.tsx]
[D:\Workspace\www\fanstore\workspace\my-app\http.mjs]
[D:\Workspace\www\fanstore\workspace\my-app\http.js]
[D:\Workspace\www\fanstore\workspace\node_modules\faunadb\src\node_modules]
[D:\Workspace\www\fanstore\workspace\node_modules\faunadb\node_modules]
[D:\Workspace\www\fanstore\workspace\node_modules\node_modules]
[D:\Workspace\www\fanstore\node_modules]
[D:\Workspace\www\node_modules]
[D:\Workspace\node_modules]
[D:\node_modules]
[D:\Workspace\www\fanstore\workspace\node_modules\package.json]
[D:\Workspace\www\fanstore\workspace\node_modules\http\package.json]
[D:\Workspace\www\fanstore\workspace\node_modules\http]
[D:\Workspace\www\fanstore\workspace\node_modules\http.ts]
[D:\Workspace\www\fanstore\workspace\node_modules\http.tsx]
[D:\Workspace\www\fanstore\workspace\node_modules\http.mjs]
[D:\Workspace\www\fanstore\workspace\node_modules\http.js]
 @ ../node_modules/faunadb/src/Client.js 87:8-23
 @ ../node_modules/faunadb/index.js
 @ ./src/app/app.component.ts
 @ ./src/app/app.module.ngfactory.js
 @ ./src/main.ts
 @ multi ./src/main.ts
ERROR in ../node_modules/faunadb/src/Client.js
Module not found: Error: Can't resolve 'https' in 'D:\Workspace\www\fanstore\workspace\node_modules\faunadb\src'
resolve 'https' in 'D:\Workspace\www\fanstore\workspace\node_modules\faunadb\src'
  Parsed request is a module
  using description file: D:\Workspace\www\fanstore\workspace\node_modules\faunadb\package.json (relative path: ./src)
    Field 'browser' doesn't contain a valid alias configuration
    resolve as module
      looking for modules in D:/Workspace/www/fanstore/workspace/my-app/
        using description file: D:\Workspace\www\fanstore\workspace\my-app\package.json (relative path: .)
          Field 'browser' doesn't contain a valid alias configuration
          using description file: D:\Workspace\www\fanstore\workspace\my-app\package.json (relative path: ./https)
            no extension
              Field 'browser' doesn't contain a valid alias configuration
              D:\Workspace\www\fanstore\workspace\my-app\https doesn't exist
            .ts
              Field 'browser' doesn't contain a valid alias configuration
              D:\Workspace\www\fanstore\workspace\my-app\https.ts doesn't exist
            .tsx
              Field 'browser' doesn't contain a valid alias configuration
              D:\Workspace\www\fanstore\workspace\my-app\https.tsx doesn't exist
            .mjs
              Field 'browser' doesn't contain a valid alias configuration
              D:\Workspace\www\fanstore\workspace\my-app\https.mjs doesn't exist
            .js
              Field 'browser' doesn't contain a valid alias configuration
              D:\Workspace\www\fanstore\workspace\my-app\https.js doesn't exist
            as directory
              D:\Workspace\www\fanstore\workspace\my-app\https doesn't exist
      D:\Workspace\www\fanstore\workspace\node_modules\faunadb\src\node_modules doesn't exist or is not a directory
      D:\Workspace\www\fanstore\workspace\node_modules\faunadb\node_modules doesn't exist or is not a directory
      D:\Workspace\www\fanstore\workspace\node_modules\node_modules doesn't exist or is not a directory
      D:\Workspace\www\fanstore\node_modules doesn't exist or is not a directory
      D:\Workspace\www\node_modules doesn't exist or is not a directory
      D:\Workspace\node_modules doesn't exist or is not a directory
      D:\node_modules doesn't exist or is not a directory
      looking for modules in D:\Workspace\www\fanstore\workspace\node_modules
        No description file found
        Field 'browser' doesn't contain a valid alias configuration
        No description file found
        no extension
          Field 'browser' doesn't contain a valid alias configuration
          D:\Workspace\www\fanstore\workspace\node_modules\https doesn't exist
        .ts
          Field 'browser' doesn't contain a valid alias configuration
          D:\Workspace\www\fanstore\workspace\node_modules\https.ts doesn't exist
        .tsx
          Field 'browser' doesn't contain a valid alias configuration
          D:\Workspace\www\fanstore\workspace\node_modules\https.tsx doesn't exist
        .mjs
          Field 'browser' doesn't contain a valid alias configuration
          D:\Workspace\www\fanstore\workspace\node_modules\https.mjs doesn't exist
        .js
          Field 'browser' doesn't contain a valid alias configuration
          D:\Workspace\www\fanstore\workspace\node_modules\https.js doesn't exist
        as directory
          D:\Workspace\www\fanstore\workspace\node_modules\https doesn't exist
[D:\Workspace\www\fanstore\workspace\my-app\https]
[D:\Workspace\www\fanstore\workspace\my-app\https.ts]
[D:\Workspace\www\fanstore\workspace\my-app\https.tsx]
[D:\Workspace\www\fanstore\workspace\my-app\https.mjs]
[D:\Workspace\www\fanstore\workspace\my-app\https.js]
[D:\Workspace\www\fanstore\workspace\node_modules\faunadb\src\node_modules]
[D:\Workspace\www\fanstore\workspace\node_modules\faunadb\node_modules]
[D:\Workspace\www\fanstore\workspace\node_modules\node_modules]
[D:\Workspace\www\fanstore\node_modules]
[D:\Workspace\www\node_modules]
[D:\Workspace\node_modules]
[D:\node_modules]
[D:\Workspace\www\fanstore\workspace\node_modules\package.json]
[D:\Workspace\www\fanstore\workspace\node_modules\https\package.json]
[D:\Workspace\www\fanstore\workspace\node_modules\https]
[D:\Workspace\www\fanstore\workspace\node_modules\https.ts]
[D:\Workspace\www\fanstore\workspace\node_modules\https.tsx]
[D:\Workspace\www\fanstore\workspace\node_modules\https.mjs]
[D:\Workspace\www\fanstore\workspace\node_modules\https.js]
 @ ../node_modules/faunadb/src/Client.js 86:8-24
 @ ../node_modules/faunadb/index.js
 @ ./src/app/app.component.ts
 @ ./src/app/app.module.ngfactory.js
 @ ./src/main.ts
 @ multi ./src/main.ts
ERROR in ../node_modules/faunadb/src/errors.js
Module not found: Error: Can't resolve 'util' in 'D:\Workspace\www\fanstore\workspace\node_modules\faunadb\src'
resolve 'util' in 'D:\Workspace\www\fanstore\workspace\node_modules\faunadb\src'
  Parsed request is a module
  using description file: D:\Workspace\www\fanstore\workspace\node_modules\faunadb\package.json (relative path: ./src)
    Field 'browser' doesn't contain a valid alias configuration
    resolve as module
      looking for modules in D:/Workspace/www/fanstore/workspace/my-app/
        using description file: D:\Workspace\www\fanstore\workspace\my-app\package.json (relative path: .)
          Field 'browser' doesn't contain a valid alias configuration
          using description file: D:\Workspace\www\fanstore\workspace\my-app\package.json (relative path: ./util)
            no extension
              Field 'browser' doesn't contain a valid alias configuration
              D:\Workspace\www\fanstore\workspace\my-app\util doesn't exist
            .ts
              Field 'browser' doesn't contain a valid alias configuration
              D:\Workspace\www\fanstore\workspace\my-app\util.ts doesn't exist
            .tsx
              Field 'browser' doesn't contain a valid alias configuration
              D:\Workspace\www\fanstore\workspace\my-app\util.tsx doesn't exist
            .mjs
              Field 'browser' doesn't contain a valid alias configuration
              D:\Workspace\www\fanstore\workspace\my-app\util.mjs doesn't exist
            .js
              Field 'browser' doesn't contain a valid alias configuration
              D:\Workspace\www\fanstore\workspace\my-app\util.js doesn't exist
            as directory
              D:\Workspace\www\fanstore\workspace\my-app\util doesn't exist
      D:\Workspace\www\fanstore\workspace\node_modules\faunadb\src\node_modules doesn't exist or is not a directory
      D:\Workspace\www\fanstore\workspace\node_modules\faunadb\node_modules doesn't exist or is not a directory
      D:\Workspace\www\fanstore\workspace\node_modules\node_modules doesn't exist or is not a directory
      D:\Workspace\www\fanstore\node_modules doesn't exist or is not a directory
      D:\Workspace\www\node_modules doesn't exist or is not a directory
      D:\Workspace\node_modules doesn't exist or is not a directory
      D:\node_modules doesn't exist or is not a directory
      looking for modules in D:\Workspace\www\fanstore\workspace\node_modules
        No description file found
        Field 'browser' doesn't contain a valid alias configuration
        No description file found
        no extension
          Field 'browser' doesn't contain a valid alias configuration
          D:\Workspace\www\fanstore\workspace\node_modules\util doesn't exist
        .ts
          Field 'browser' doesn't contain a valid alias configuration
          D:\Workspace\www\fanstore\workspace\node_modules\util.ts doesn't exist
        .tsx
          Field 'browser' doesn't contain a valid alias configuration
          D:\Workspace\www\fanstore\workspace\node_modules\util.tsx doesn't exist
        .mjs
          Field 'browser' doesn't contain a valid alias configuration
          D:\Workspace\www\fanstore\workspace\node_modules\util.mjs doesn't exist
        .js
          Field 'browser' doesn't contain a valid alias configuration
          D:\Workspace\www\fanstore\workspace\node_modules\util.js doesn't exist
        as directory
          D:\Workspace\www\fanstore\workspace\node_modules\util doesn't exist
[D:\Workspace\www\fanstore\workspace\my-app\util]
[D:\Workspace\www\fanstore\workspace\my-app\util.ts]
[D:\Workspace\www\fanstore\workspace\my-app\util.tsx]
[D:\Workspace\www\fanstore\workspace\my-app\util.mjs]
[D:\Workspace\www\fanstore\workspace\my-app\util.js]
[D:\Workspace\www\fanstore\workspace\node_modules\faunadb\src\node_modules]
[D:\Workspace\www\fanstore\workspace\node_modules\faunadb\node_modules]
[D:\Workspace\www\fanstore\workspace\node_modules\node_modules]
[D:\Workspace\www\fanstore\node_modules]
[D:\Workspace\www\node_modules]
[D:\Workspace\node_modules]
[D:\node_modules]
[D:\Workspace\www\fanstore\workspace\node_modules\package.json]
[D:\Workspace\www\fanstore\workspace\node_modules\util\package.json]
[D:\Workspace\www\fanstore\workspace\node_modules\util]
[D:\Workspace\www\fanstore\workspace\node_modules\util.ts]
[D:\Workspace\www\fanstore\workspace\node_modules\util.tsx]
[D:\Workspace\www\fanstore\workspace\node_modules\util.mjs]
[D:\Workspace\www\fanstore\workspace\node_modules\util.js]
 @ ../node_modules/faunadb/src/errors.js 3:11-26
 @ ../node_modules/faunadb/index.js
 @ ./src/app/app.component.ts
 @ ./src/app/app.module.ngfactory.js
 @ ./src/main.ts
 @ multi ./src/main.ts
ERROR in ../node_modules/faunadb/src/values.js
Module not found: Error: Can't resolve 'util' in 'D:\Workspace\www\fanstore\workspace\node_modules\faunadb\src'
resolve 'util' in 'D:\Workspace\www\fanstore\workspace\node_modules\faunadb\src'
  Parsed request is a module
  using description file: D:\Workspace\www\fanstore\workspace\node_modules\faunadb\package.json (relative path: ./src)
    Field 'browser' doesn't contain a valid alias configuration
    resolve as module
      looking for modules in D:/Workspace/www/fanstore/workspace/my-app/
        using description file: D:\Workspace\www\fanstore\workspace\my-app\package.json (relative path: .)
          Field 'browser' doesn't contain a valid alias configuration
          using description file: D:\Workspace\www\fanstore\workspace\my-app\package.json (relative path: ./util)
            no extension
              Field 'browser' doesn't contain a valid alias configuration
              D:\Workspace\www\fanstore\workspace\my-app\util doesn't exist
            .ts
              Field 'browser' doesn't contain a valid alias configuration
              D:\Workspace\www\fanstore\workspace\my-app\util.ts doesn't exist
            .tsx
              Field 'browser' doesn't contain a valid alias configuration
              D:\Workspace\www\fanstore\workspace\my-app\util.tsx doesn't exist
            .mjs
              Field 'browser' doesn't contain a valid alias configuration
              D:\Workspace\www\fanstore\workspace\my-app\util.mjs doesn't exist
            .js
              Field 'browser' doesn't contain a valid alias configuration
              D:\Workspace\www\fanstore\workspace\my-app\util.js doesn't exist
            as directory
              D:\Workspace\www\fanstore\workspace\my-app\util doesn't exist
      D:\Workspace\www\fanstore\workspace\node_modules\faunadb\src\node_modules doesn't exist or is not a directory
      D:\Workspace\www\fanstore\workspace\node_modules\faunadb\node_modules doesn't exist or is not a directory
      D:\Workspace\www\fanstore\workspace\node_modules\node_modules doesn't exist or is not a directory
      D:\Workspace\www\fanstore\node_modules doesn't exist or is not a directory
      D:\Workspace\www\node_modules doesn't exist or is not a directory
      D:\Workspace\node_modules doesn't exist or is not a directory
      D:\node_modules doesn't exist or is not a directory
      looking for modules in D:\Workspace\www\fanstore\workspace\node_modules
        No description file found
        Field 'browser' doesn't contain a valid alias configuration
        No description file found
        no extension
          Field 'browser' doesn't contain a valid alias configuration
          D:\Workspace\www\fanstore\workspace\node_modules\util doesn't exist
        .ts
          Field 'browser' doesn't contain a valid alias configuration
          D:\Workspace\www\fanstore\workspace\node_modules\util.ts doesn't exist
        .tsx
          Field 'browser' doesn't contain a valid alias configuration
          D:\Workspace\www\fanstore\workspace\node_modules\util.tsx doesn't exist
        .mjs
          Field 'browser' doesn't contain a valid alias configuration
          D:\Workspace\www\fanstore\workspace\node_modules\util.mjs doesn't exist
        .js
          Field 'browser' doesn't contain a valid alias configuration
          D:\Workspace\www\fanstore\workspace\node_modules\util.js doesn't exist
        as directory
          D:\Workspace\www\fanstore\workspace\node_modules\util doesn't exist
[D:\Workspace\www\fanstore\workspace\my-app\util]
[D:\Workspace\www\fanstore\workspace\my-app\util.ts]
[D:\Workspace\www\fanstore\workspace\my-app\util.tsx]
[D:\Workspace\www\fanstore\workspace\my-app\util.mjs]
[D:\Workspace\www\fanstore\workspace\my-app\util.js]
[D:\Workspace\www\fanstore\workspace\node_modules\faunadb\src\node_modules]
[D:\Workspace\www\fanstore\workspace\node_modules\faunadb\node_modules]
[D:\Workspace\www\fanstore\workspace\node_modules\node_modules]
[D:\Workspace\www\fanstore\node_modules]
[D:\Workspace\www\node_modules]
[D:\Workspace\node_modules]
[D:\node_modules]
[D:\Workspace\www\fanstore\workspace\node_modules\package.json]
[D:\Workspace\www\fanstore\workspace\node_modules\util\package.json]
[D:\Workspace\www\fanstore\workspace\node_modules\util]
[D:\Workspace\www\fanstore\workspace\node_modules\util.ts]
[D:\Workspace\www\fanstore\workspace\node_modules\util.tsx]
[D:\Workspace\www\fanstore\workspace\node_modules\util.mjs]
[D:\Workspace\www\fanstore\workspace\node_modules\util.js]
 @ ../node_modules/faunadb/src/values.js 7:11-26
 @ ../node_modules/faunadb/index.js
 @ ./src/app/app.component.ts
 @ ./src/app/app.module.ngfactory.js
 @ ./src/main.ts
 @ multi ./src/main.ts
[ERROR] An error occurred while running subprocess ng.

        ng.cmd run app:build:production exited with exit code 1.

        Re-running this command with the --verbose flag may provide more information.

q.Lambda behaves differently depending on the number of arguments

Hi,

Currently:
q.Lambda(foo => foo) generates Lambda("foo", Var("foo"))
q.Lambda((foo, bar) => foo) generates Lambda(["foo", "bar"], Var("foo"))

As Lambda("foo", Var("foo")) and Lambda(["foo"], Var("foo")) are not the same, shouldn't it be more coherent to have q.Lambda(foo => foo) generates Lambda(["foo"], Var("foo")) then ?

Cheers!

PS: Context: It made me struggle about why my grapghQL custom resolver with a single argument was not working, whereas with multiple ones it worked.

TypeScript version

Upcoming TypeScript version is a chance to do things right. Sure we can have typed API with TypeScript compiler checking the right composition, that's standard, but we should be able to enforce types even for runtime. Fauna is awesome but as any document DB, any shape approach can accidentally harm the developer. In the end, we need types. But can we blindly believe that our database will return what we expect? Never. Any serious application needs to validate/parse values out of the application boundary. Period.

That's why https://github.com/gcanti/io-ts is such an awesome library. Mature, well-tested, well-designed.

I highly recommend to check it and use it for development TypeScript version of faunadb driver.

For example, this is the FaunaID type I am using. And I will need FaunaRef generic type. And types for Fauna errors. Etc.

interface FaunaIDBrand {
  readonly FaunaID: unique symbol;
}
export const FaunaID = t.brand(
  t.string,
  (s): s is t.Branded<string, FaunaIDBrand> => /^\d+$/.test(s),
  'FaunaID',
);
export type FaunaID = t.TypeOf<typeof FaunaID>;

I would love to help with any issue regarding TypeScript version design.

Revisit PasalCase?

Can we please revisit the matter of PascalCase versus lowerCamelCase?

It was originally raised by @alexeygolev in #100, but I don't think that the motivation to 'unify the feel of the drivers across languages' is ultimately worthwhile to justify PascalCase over lowerCamelCase.

FaunaDB is not the first project to have drivers in multiple languages. In many other projects, they opt to conform to the idioms of each language. For instance, RethinkDB has four official language drivers for its ReQL query language - JavaScript, Python, Ruby, and Java - and each conform to the idioms of their language. There's no doubt that you're writing ReQL in each case, and its concepts remain reasonably consistent for each. It's not clear why Fauna should be any different.

It's also important to consider that Fauna does not exist in a vacuum. The driver is going to be interspersed amongst other JavaScript code and libraries, the majority of which use lowerCamelCase. Thus, the coding style will be inescapably inconsistent, which is disorientating.

It's also unclear who benefits from having a 'unified feel' across languages. The people most likely to use a JavaScript library are JavaScript developers, who will be well-acquainted with lowerCamelCase. Further, even if a non-JavaScript developer were to view a JavaScript Fauna query and attempt to understand it, identifier casing is a minor confusion compared with the confusion of understanding aspects of JavaScript syntax which Fauna can't control, like async and arrow functions. I do not see any reason why lowerCamelCase would prevent someone from understanding a JavaScript Fauna query. The Fauna query language shines through, regardless of identifier casing.

Although I did not see this mentioned in the previous discussion, I can understand how using lowerCamelCase could entail a somewhat greater cost in maintenance of the driver and related documentation. However, I would feel that this is the sort of matter where you bear the cost to reap the benefits of having happier and more comfortable developers. Again, other projects seem to have made that calculation and deemed it worthwhile.

Ultimately, the query language is a really critical component of a database. It's the language through which the developer communicates with the database. It's the most tangible manifestation of the database for them. So, it's important that it works well for them, and that they're comfortable using it. Currently, PascalCase might well put off quite a few developers, and as said here, there does not seem to be much reason to do this in the grand scheme of things.

Client should handle errors like 413

When the body becomes too large (1MB?) you get an 413 error returned from nginx with html in the body. The fauna client tries to parse the result as JSON resulting in a Unexpected token < in JSON at position 0 error.

Requiring 'faunadb' from the package installed from npm fails

Depending on faunadb as such:

  "dependencies": {
    "faunadb": "git+ssh://[email protected]/faunadb/faunadb-js.git",
  }

then using it:

var faunadb = require('faunadb');

fails:

module.js:341
    throw err;
    ^

Error: Cannot find module './lib/model/Codec'
    at Function.Module._resolveFilename (module.js:339:15)
    at Function.Module._load (module.js:290:25)
    at Module.require (module.js:367:17)
    at require (internal/module.js:16:19)
    at /home/eac/fauna/consulting/breezeworks/load/node_modules/faunadb/index.js:7:16
    at Array.forEach (native)
    at Object.<anonymous> (/home/eac/fauna/consulting/breezeworks/load/node_modules/faunadb/index.js:6:15)
    at Module._compile (module.js:413:34)
    at Object.Module._extensions..js (module.js:422:10)
    at Module.load (module.js:357:32)

The relative paths here are problematic.

Default class for types is unnecessary

I was playing around with TypeScript and the faundb js client today and no matter what I tried, the following line was giving me problems in my text editor.

import * as faunadb from 'faunadb';
const client = new faunadb.Client({
  secret: credentials.faunadbSecret
});

The error message was that the property 'Client' does not exist on faunadb.

Once I went into the type definitions for the client and changed the definition from export default class Client to export class Client, things started working.

Can you confirm that the above change should be made to this repo (as well as all the other default class types) or am I missing something in my implementation?

firebase-functions typescript cannot find name 'fetch'

Adding faunadb to firebase functions typescript, and when I use import as so:
import * as faunadb from 'faunadb';
it throws an error when deploying

node_modules/faunadb/src/types/Client.d.ts:14:18 - error TS2304: Cannot find name 'fetch'.

14   fetch?: typeof fetch

I can't seem to use
import faunadb, {q as query} from 'faunadb';
this says throws Module '".../node_modules/faunadb/index"' has no default export.
Here is the npm log

0 info it worked if it ends with ok
1 verbose cli [
1 verbose cli   '/home/<user>/.nvm/versions/node/v12.16.2/bin/node',
1 verbose cli   '/home/<user>/.nvm/versions/node/v12.16.2/bin/npm',
1 verbose cli   '--prefix',
1 verbose cli   '/home/<user>/dev/work/<project>/<functions-directory>/functions',
1 verbose cli   'run',
1 verbose cli   'build'
1 verbose cli ]
2 info using [email protected]
3 info using [email protected]
4 verbose run-script [ 'prebuild', 'build', 'postbuild' ]
5 info lifecycle functions@~prebuild: functions@
6 info lifecycle functions@~build: functions@
7 verbose lifecycle functions@~build: unsafe-perm in lifecycle true
8 verbose lifecycle functions@~build: PATH: /home/<user>/.nvm/versions/node/v12.16.2/lib/node_modules/npm/node_modules/npm-lifecycle/node-gyp-bin:/home/<user>/dev/work/<project>/<functions-directory>/functions/node_modules/.bin:/home/<user>/.nvm/versions/node/v12.16.2/bin:/home/<user>/.local/bin:/home/<user>/.local/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/lib/jvm/default/bin:/usr/bin/site_perl:/usr/bin/vendor_perl:/usr/bin/core_perl:/var/lib/snapd/snap/bin:/usr/lib/jvm/default/bin:/usr/bin/site_perl:/usr/bin/vendor_perl:/usr/bin/core_perl:/home/<user>/dev/lib/flutter/bin:/home/<user>/dev/lib/flutter/bin
9 verbose lifecycle functions@~build: CWD: /home/<user>/dev/work/<project>/<functions-directory>/functions
10 silly lifecycle functions@~build: Args: [ '-c', 'tsc' ]
11 silly lifecycle functions@~build: Returned: code: 2  signal: null
12 info lifecycle functions@~build: Failed to exec build script
13 verbose stack Error: functions@ build: `tsc`
13 verbose stack Exit status 2
13 verbose stack     at EventEmitter.<anonymous> (/home/<user>/.nvm/versions/node/v12.16.2/lib/node_modules/npm/node_modules/npm-lifecycle/index.js:332:16)
13 verbose stack     at EventEmitter.emit (events.js:310:20)
13 verbose stack     at ChildProcess.<anonymous> (/home/<user>/.nvm/versions/node/v12.16.2/lib/node_modules/npm/node_modules/npm-lifecycle/lib/spawn.js:55:14)
13 verbose stack     at ChildProcess.emit (events.js:310:20)
13 verbose stack     at maybeClose (internal/child_process.js:1021:16)
13 verbose stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:286:5)
14 verbose pkgid functions@
15 verbose cwd /home/<user>/dev/work/<project>/<functions-directory>
16 verbose Linux 5.4.33-3-MANJARO
17 verbose argv "/home/<user>/.nvm/versions/node/v12.16.2/bin/node" "/home/<user>/.nvm/versions/node/v12.16.2/bin/npm" "--prefix" "/home/<user>/dev/work/<project>/<functions-directory>/functions" "run" "build"
18 verbose node v12.16.2
19 verbose npm  v6.14.4
20 error code ELIFECYCLE
21 error errno 2
22 error functions@ build: `tsc`
22 error Exit status 2
23 error Failed at the functions@ build script.
23 error This is probably not a problem with npm. There is likely additional logging output above.
24 verbose exit [ 2, true ]

It however works perfectly when I use require

Multi-Argument Ref() constructor concats terms in JS

You can't express the construction of a Ref with a fauna-generated ID, because JS will try to concat the terms in code.

So, for example, saying q.Ref("classes/some_class", q.NextId()) will send a ref to the DB of "classes/some_class/[object]" or something where [object] is the stringification of the q.NextId() object.

very confuse JSON response

Im creating a collection in my code with something like the example in the docs:

q.CreateCollection({ name: 'users' })

the response in my api is :

{"error":"The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type undefined"}

but the collection its created anyway. i dont get that. if the collection is created successfully, why that message ?

then i create an Index :
q.CreateIndex(
{
name: "users_by_email",
source: q.Collection("users"),
terms: [{ field: ["data", "email"] }],
unique: true
})
Response :
{"error":"The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type undefined"}

The index is created anyway the response. It is very confused to know if is success or not.

Change Page class

Move it to its own file.
Page doesn't need to be convertible to JSON.

Error trying to use in a Cloudflare Worker

I'm seeing the following error while trying to use the driver in a Cloudflare Worker:

ReferenceError: XMLHttpRequest is not defined

This is making it impossible to use Fauna from Cloudflare Workers, unless there's some workaround that I haven't yet considered.

@aequasi Sounds like you're using Workers, are you seeing this issue?

Note: Originally opened this issue on the closed #182 but then realized it's likely best to create a new issue for it.

Paginate not working with indexes with terms

I have these indexes:

{
  "name": "all_beverages",
  "source": q.Class("beverages"),
  "values": [
    {"field": ["data", "name"]},
    {"field": ["ref"]}
  ]
}
{
  "name": "beverages_by_type",
  "source": q.Class("beverages"),
  "values": [
    {"field": ["ref"]},
    {
      "field": ["data", "name"]
    }
  ],
  "terms": [
    {"field": ["data", "type"]}
  ]
}

When I do a query with paginate to the first one, I get all the results as expected:

const pager = await faunaClient.paginate(q.Match(q.Index('all_beverages')));
pager.map(ref => this.q.Get(ref)).each(doc => {
    console.log('doc', doc);
});

But if I do the same with the other index + a value I get no results:

const pager = await faunaClient.paginate(q.Match(q.Index('beverages_by_type'), 'beer'));
pager.map(ref => this.q.Get(ref)).each(doc => {
    console.log('doc', doc);
});

I've tried the indexes directly in Dashboard's Query Console and they worked fine.

If I do the same without the paginate method, it works perfect:

faunaClient.query(q.Paginate(q.Match(q.Index('beverages_by_type'), 'beer')))
.then(ret => console.log(ret));

Not sure if something is wrong in my paginate method usage or what.

Docs in TypeScript annotations

It would immensely improve DX.

Btw, why this lib is not written in TypeScript? I can help you with design and transition. It's really worth it.

breaking change on v2.14.0

When I upgrade from v2.13.0 to v2.14.0 the faunadb query returns with a non-JSON.
The same code in 2.13.0 works just fine.

Environment: Localhost
it is a "lambda function"

export default async function org(req, res) {
  const adminClient = new faunadb.Client({
    secret: process.env.FAUNADB_SECRET,
    keepAlive: false,
  });

  const host = req?.headers['host'];
  const subdomain = getSubdomain({
    host,
    processSubdomain: process.env.SUBDOMAIN,
  });

  try {
    const matches = await adminClient.query(
      q.Paginate(
        q.Match(q.Index('orgsSecretByNameSpace'), q.Casefold(subdomain)),
      ),
    );
    const serverSecret = matches?.data[0];

    const childClient = new faunadb.Client({
      secret: serverSecret,
      keepAlive: false,
    });

    const settingsList = await childClient.query(
      q.Map(q.Paginate(q.Match(q.Index('settings'))), setting =>
        q.Select(['data'], q.Get(setting)),
      ),
    );

    const settings = keyBy(settingsList?.data || [], 'id');

    res.json({ settings, serverSecret, subdomain });
  } catch (error) {
    console.error(error);

    res.status(error.status || 500).json({
      error: error.message,
    });
  }
}```

Throwing error in serverless function.

? new require(opts.scheme).Agent({ keepAlive: true })

is attempting to require dynamically.
This seems to warn during build of a serverless function (tested with Netlify) :

WARNING in /node_modules/faunadb/src/Client.js 73:24-48
Critical dependency: the request of a dependency is an expression

and ultimately an error on execution :

Response with status 500 in 132 ms.
Error during invocation:  { Error: Cannot find module 'https'

Do I need a specific webpack configuration?

Temp fix for unserializable models

Fauna driver uses models which are serialized into incompatible objects. For example, Ref id handled via getter is missing when a model is serialized. And we can not read serialized props until a model is serialized. It's like Catch-22.

The temporal fix is to use JSON.parse(JSON.stringify(object)) to get plain row JSON without unserializable getters.

Hope this will help someone.

Expose parseJSON

It would be useful if parseJSON was exposed so we can deserialize Ref object for example.

Current workaround:

import { parseJSON } from 'faunadb/src/_json'

Pascal case for query methods

Is there any particular reason for pascal case in query methods? Normally one would assume pascal case signifies a class/constructor function (in fact faunadb.Client is indeed a class called with new) which can be confusing. Another con is that in case of Map you can't do

import { Client, query } from 'fauna'
const { Map } = query

[bug] npm install fauna/faunadb-js breaks

Problem seems to be with 6.0+ versions of babel.

First error

The CLI has been moved into the package `babel-cli`.
$ npm install -g babel-cli

Once installed the second error is

ReferenceError: [BABEL] src/AsyncStream.js: Unknown option: project/node_modules/faunadb/package.json.optional
    at Logger.error (project/node_modules/babel-cli/node_modules/babel-core/lib/transformation/file/logger.js:43:11)
    at OptionManager.mergeOptions (project/node_modules/babel-cli/node_modules/babel-core/lib/transformation/file/options/option-manager.js:245:18)
    at OptionManager.addConfig (project/node_modules/babel-cli/node_modules/babel-core/lib/transformation/file/options/option-manager.js:206:10)
    at OptionManager.findConfigs (project/node_modules/babel-cli/node_modules/babel-core/lib/transformation/file/options/option-manager.js:353:16)
    at OptionManager.init (project/node_modules/babel-cli/node_modules/babel-core/lib/transformation/file/options/option-manager.js:392:12)
    at File.initOptions (project/node_modules/babel-cli/node_modules/babel-core/lib/transformation/file/index.js:191:75)
    at new File (project/node_modules/babel-cli/node_modules/babel-core/lib/transformation/file/index.js:122:22)
    at Pipeline.transform (project/node_modules/babel-cli/node_modules/babel-core/lib/transformation/pipeline.js:42:16)
    at transform (project/node_modules/babel-cli/lib/babel/util.js:53:22)
    at Object.compile (project/node_modules/babel-cli/lib/babel/util.js:62:12)

Installing [email protected] before running npm install fauna/faunadb-js gets around this issue, but is not a very good long term solution.

connect ETIMEDOUT 52.214.123.134:443

I really tired with this error:

request to https://db.fauna.com/ failed, reason: connect ETIMEDOUT 52.214.123.134:443

Sometime I receive this!!!

[bug] `require('faunadb')` or `import faunadb from 'faunadb'` throws an error

The following error is being thrown when doing import faunadb from "faunadb"

Error: Cannot find module 'faunadb'
    at Function.Module._resolveFilename (module.js:336:15)
    at Function.Module._load (module.js:286:25)
    at Module.require (module.js:365:17)
    at require (module.js:384:17)
    at Object.<anonymous> (/Users/dremonkey/Projects/Javascript/skystream/app/index.js:5:36)
    at Module._compile (module.js:434:26)
    at normalLoader (/Users/dremonkey/Projects/Javascript/skystream/node_modules/babel/node_modules/babel-core/lib/api/register/node.js:199:5)
    at Object.require.extensions.(anonymous function) [as .js] (/Users/dremonkey/Projects/Javascript/skystream/node_modules/babel/node_modules/babel-core/lib/api/register/node.js:216:7)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)

This is caused because there is no index.js file at the toplevel of the faunadb directory or main entry in package.json. From looking at your example I assume you already know this, but for somebody new to the library it isn't clear how exactly one should go about using it.

There are three possible solutions to this... just going to present them so you can choose which you want to go with.

  1. Create a top level index.js file and use it to expose at the very least the Client class. I'm not sure what else you would like to expose.... Model maybe?
  2. Add the main property to package.json that points at one of the files... maybe lib/Client if that is all you want to expose or create a lib/index.js file and point it there.
  3. Mention in the README that in order to actually use Client or Model or any of the others you have to import it directly var Client = require("faunadb/lib/Client") or import Client from "faunadb/lib/Client")

The first or second option is probably the method I've seen used most in other node libraries... implementation becomes pretty straightforward too...

import faunadb as "faunadb";

let Client = faunadb.Client;
let Model = faunadb.Model;

Socket hang up error sometimes

Sometimes I get a socket hangup error from faunadb in my netlify function:

12:36:29 PM: 2020-02-13T11:36:29.083Z	00e2d3c8-39f5-48e4-b5c2-4341629d4ef9	ERROR	FetchError: request to https://db.fauna.com/ failed, reason: socket hang up
    at ClientRequest.<anonymous> (/var/task/node_modules/node-fetch/lib/index.js:1455:11)
    at ClientRequest.emit (events.js:223:5)
    at TLSSocket.socketOnEnd (_http_client.js:440:9)
    at TLSSocket.emit (events.js:228:7)
    at endReadableNT (_stream_readable.js:1185:12)
    at processTicksAndRejections (internal/process/task_queues.js:81:21) {
  message: 'request to https://db.fauna.com/ failed, reason: socket hang up',
  type: 'system',
  errno: 'ECONNRESET',
  code: 'ECONNRESET'
}

Tested with 2.9.2

How to query the corresponding data?

CRUD - how to realize sql

select * from table_name where "body" like "%hello%"

Corresponding the operation

Query by field content ,

Pagination queries are paginated based on the number of rows, not by id?

I looked at the documentation but couldn't find the appropriate method
The example given is too vague, I hope you can improve it

example

image

http://ww1.sinaimg.cn/large/7fe73d0agy1gel9vc195xj219u074gls.jpg
image
http://ww1.sinaimg.cn/large/7fe73d0agy1gela0j94p2j20ne0eignb.jpg

require is not a function

I am receiving these errors when I deploy to serverless.
I am using webpack and typescript with faunadb.
Whenever I import faunadb and get query I get these errors.

WARNING in ./~/formidable/lib/incoming_form.js
Critical dependencies:
1:43-50 require function is used in a way in which dependencies cannot be statically extracted
 @ ./~/formidable/lib/incoming_form.js 1:43-50

WARNING in ./~/formidable/lib/json_parser.js
Critical dependencies:
1:43-50 require function is used in a way in which dependencies cannot be statically extracted
 @ ./~/formidable/lib/json_parser.js 1:43-50

WARNING in ./~/formidable/lib/file.js
Critical dependencies:
1:43-50 require function is used in a way in which dependencies cannot be statically extracted
 @ ./~/formidable/lib/file.js 1:43-50

WARNING in ./~/formidable/lib/querystring_parser.js
Critical dependencies:
1:43-50 require function is used in a way in which dependencies cannot be statically extracted
 @ ./~/formidable/lib/querystring_parser.js 1:43-50

And when i run get require is not defined. So serverless then defaults to an internal server error.

The script goes as follows

import { db } from '../db/client';
import * as faunadb from 'faunadb';
import { Application } from '../../system/app';

const q = faunadb.query; // <--- this is the line that breaks it. If i comment out it works.

error inspect should include query

when you get an error it tells you everything you don't need, but by default node.js elides the actual query content. We should make that more visible somehow.

Example of the frustrating output:

{ [BadRequest: instance not unique]
  name: 'BadRequest',
  message: 'instance not unique',
  requestResult: 
   RequestResult {
     client: 
      Client {
        _baseUrl: 'https://db.fauna.com:443',
        _timeout: 60000,
        _secret: 'fnACbtkm0AACAP4-yv8-KAtqnCxs5a-y88c37I89',
        _observer: null },
     method: 'POST',
     path: '',
     query: null,
     requestContent: Expr { raw: [Object] },
     responseRaw: '{"errors":[{"position":["foreach","expr"],"code":"instance not unique","description":"Instance is not unique."}]}',
     responseContent: { errors: [Array] },
     statusCode: 400,
     responseHeaders: 
      { 'content-type': 'application/json;charset=utf-8',
        date: 'Wed, 23 Aug 2017 01:58:30 GMT',
        'x-bus-bytes-in': '0',
        'x-bus-bytes-out': '0',
        'x-bus-messages-in': '0',
        'x-bus-messages-out': '0',
        'x-compute-stack-depth': '817',
        'x-compute-stack-frames': '0',
        'x-faunadb-build': '2.1.26-e653ae5',
        'x-faunadb-host': 'ec2-54-202-130-208.us-west-2.compute.amazonaws.com',
        'x-points-network-in': '1.12',
        'x-points-network-out': '0.05',
        'x-points-storage-read': '5.7',
        'x-points-storage-write': '18.2',
        'x-points-total': '25.07',
        'x-query-bytes-in': '2302',
        'x-query-bytes-out': '113',
        'x-query-time': '12322',
        'x-storage-bytes-read': '15545',
        'x-storage-bytes-write': '3367',
        'x-storage-ops-delete': '91',
        'x-storage-ops-read': '114',
        'x-storage-ops-write': '91',
        'content-length': '113',
        connection: 'Close' },
     startTime: 1503453497532,
     endTime: 1503453510003 } }

Tutorials link leads to 404

While reading up on the documentation i was trying to access the tutorials section and the link redirected me to a 404. If possible please correct the actual tutorials endpoint address on the readme file on the repository, So that the actual tutorial is shown?

Why getters

I can understand it can be handy but they are not serializable to JSON and it can lead to confusing DX.

Is there any reason I am not aware of? Thank you

Object literal as argument when calling a function fails

This query returns an error:
q.Call(q.Function('my_function'), { foo: 'bar' })

While this works.
q.Call(q.Function('my_function'), q.Object({ foo: 'bar' }))

In my particular case i want to send an array of objects to a function. My workaround is to wrap them with q.Object().
q.Call(q.Function('my_function'), [{foo: 'bar'}].map(item => q.Object(item)))

Idea: Export queries as named exports

Now we have use import { query as q } from 'faunadb'

Or const { Do, Create } = query

But it would be nice to leverage named exports with VSCode auto-import:

import { Do, Create } from 'faunadb/query'

WDYT?

Support react-native applications

Currently, the following libs and polyfills are required:

npm install --save faunadb util base-64
if (!global.btoa) {
  global.btoa = require('base-64').encode;
}

Do not override toJSON

It's super confusing that for a given object with some props, JSON.strinfigy produces an object with a different set of props. Also, I really don't see any reason to override toString but that's a minor issue.

It's hard to imagine anyone can use FaunaDB driver with this design. That's not how JavaScript/TypeScript should be written (classes, getters, toJSON/toString overrides). People serialize things all the time. With the current design, it's not even possible to serialize the simple document with Ref.

Related to #256, #222, #254

parseJSON really should not be required. Not at all and definitely not in the browser (I don't want to bundle the whole driver just for parseJSON). Hopefully, this will be addressed with the new TypeScript version.

Btw, if we really need a different type for serialization, for example, Date to a string, io-ts has a concept of Output type for such case. Check https://github.com/gcanti/io-ts-types/blob/master/src/DateFromISOString.ts

Request: Remove secret from errors

The secret is included in the requestResult of the error, which makes it extremely easy to accidentally log it or worse, include it in a result returned from the server.

Could this not be the default behavior? It feels dangerous.

Example:

{
    "code": "INTERNAL_SERVER_ERROR",
    "exception": {
        "name": "BadRequest",
        "message": "invalid argument",
        "requestResult": {
        "client": {
            "_baseUrl": "https://db.fauna.com:443",
            "_timeout": 60000,
            "_secret": "fnADai1VTfACDkPxlleU2Ri_hoAthGp3Sph_J5J9", // HERE
            "_observer": null,
            "_lastSeen": 1571270077648626,
            "_keepAlive": {
            "_events": {},
            "_eventsCount": 1,
            "defaultPort": 443,
            "protocol": "https:",
            "options": {
                "keepAlive": true,
                "path": null
            },

...

For any folks finding this from google: my workaround at the moment is something like this:

import { omit } from 'lodash';

const formatError = err => omit(err, 'requestResult.client')

Could q.Lambda generate q.Let bindings as well ?

Hi,

Currently, q.Lambda takes a function argument, which is more convenient, and takes care of the transformation of its arguments into q.Var where they are used. Nice.

But if you use a statement like const x = anExpression in the function body, in the output, x just gets replaced everywhere it's used by anExpression. Could the driver generate a q.Let (and q.Vars) call instead?

This would have the advantage of a better legibility ; and also not to compute anExpression multiple times on the DB server (unless it's already optimized for that...).

Cheers!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.