evrythng.js

evrythng.js is the official JavaScript SDK for developers writing web apps for the browser or server-side with platforms such as Node.js. It presents a fluent promise-driven API that allows programmatic access to all resources available through the standard REST API.


Installation

Here, we show a summary of the various installation methods. For detailed installation instructions, see the Installation section of the repository README.

CDN
Install with a script tag:

<script src="https://d10ka0m22z5ju5.cloudfront.net/js/evrythng/6.0.0/evrythng-6.0.0.js"></script>

Include: Available globally as evrythng

npm
Install: npm install --save evrythng
Include: Require as a dependency in the usual manner within the application JavaScript code:

const evrythng = require('evrythng');

// Or using ES6 modules
import * as evrythng from 'evrythng'

Setup Options

After it's installed, evrythng.js can be optionally configured using setup() with the following options:

  • apiUrl - String
    Change the default API host, such as https://api.us.evrythng.io/v2. If not specified, this is determined using values given for apiVersion and region.

  • fullResponse - Boolean
    Set to true to access the status or headers in responses. Can also be set on a per-request basis.

  • quiet - Boolean
    Set to true to prevent anything being output to the console.

  • geolocation - Boolean
    Set to true to ask for Geolocation when needed. When set to true, the following resources use the resolved coordinates: .action().create(), .thng().location().update(), .place().read().

  • timeout - Integer
    Set the default request timeout, in milliseconds

  • apiKey - String
    Set the authorization API key used for all raw requests

  • interceptors - Object array
    Register callbacks to be called on each request or response. We show an example in the evrythng.js repository.

  • defaultShortDomain - String
    Set the default short domain to be used when dealing with redirections.

  • apiVersion - Number
    Set which API version to use: 1 or 2. By default, apiVersion is 2. See the v2, or v1 (legacy) guide.

  • region - String
    Set region URL for defined API version. There are two supported regions: us, which is set by default, and eu.

For example, to set a global timeout and disable geolocation:

evrythng.setup({
  timeout: 5000,
  geolocation: false,
});

Scopes

The evrythng.js SDK includes scope objects that represent each type of API key and allows the developer to make requests with that key.

The following scopes for apiVersion:2 are available:

  • Operator - Operator API Key
  • AccessToken - Access Token API Key

Operator and AccessToken scopes can have a different set of permissions, which is defined by the access policy and assigned during creation of operator access and access token.

The following scopes for apiVersion:1 are available:

  • Operator - Operator API Key
  • Application - Application API Key
  • TrustedApplication - Trusted Application API Key
  • ActionApp - Application API Key
  • User - Application User API Key
  • Device - Device API Key

Most scopes are initialized in the same way by supplying the API key to use (except Device, which also requires the ID and API key):

const evrythng = require('evrythng');
const app = new evrythng.Application(APPLICATION_API_KEY);

// Or using destructuring
import { Application } from 'evrythng';
const app = new Application(APPLICATION_API_KEY);

If the scope's metadata is required immediately, use init() to ensure this data has been fetched from the API and made ready for use:

const app = new evrythng.Application(APPLICATION_API_KEY);

// Wait for scope to read its data before using its customFields
app.init()
  .then(() => console.log(app.customFields));

Making requests

All requests are made through a scope object and return promises. This provides an easy-to-read and intuitive interface to write a chain of functions to form the request. The format flows from the scope to the resource type (such as thng or collection) to the resource method.

Methods include create, read, update, delete, rescope, upsert, find, stream, and streamPages.

Resource IDs are specified in that resource's method parameter list, and payloads are specified in the request method's parameter list. For example, to update a single Thng:

const thngId = 'Um52tPXf6mshhMRRagVN2sHf';
const payload = { tags: ['updated'] };

// Using Promises
user.thng(thngId).update(payload)
  .then(console.log);

// Or async/await
const res = await user.thng(thngId).update(payload);
console.log(res);

Or to read a single page of products:

// Using Promises
operator.product().read()
  .then(console.log);

// Or async/await
const products = await operator.product().read();
console.log(products);

See the Function Reference section for a more complete list of functions.


Parameters

Request query parameters mirror those in the conventional REST API and are specified in the request as a parameter using either the params property, or chainable setters. For example, applying a filter:

// Using a params object
const params = {
  filter: 'name=Test*',
  perPage: 100,
};
operator.thng()
  .read({ params })
  .then(console.log);

// Or using chainable setters
operator.thng()
  .setFilter('name=Test*')
  .setPerPage(100)
  .read()
  .then(console.log);

Other examples of parameters specified in this way include: project, ids, perPage, withScopes, and context. We show some of these below for common scenarios:

// Specify filter as an object
const params = {
  filter: {
    name: 'Pallet*',
    tags: 'shipped',
  },
};
user.thng().read({ params })
  .then(console.log);

// Specify filters as a string
const params = { filter: 'name=Pallet*&tags=shipped' };
user.thng().read({ params })
  .then(console.log);

// Specify parameters such as project scope on creating a Thng
const projectId = 'UF6HgyNFVDswQKRRwhPK3kCg';
const payload = { name: 'Example Thng' };
const params = { project: projectId };
user.thng().create(payload, { params })
  .then(console.log);

// Receive raw HTTP fetch response instead of model entity
user.product().read({ fullResponse: true })
  .then(console.log);

// Read a single Thng with a certain tags pattern with context and scopes
const params = {
  perPage: 1,
  filter: 'tags=batch-*',
  withScopes: true,
  context: true,
};
user.action().read({ params })
  .then(console.log);

The same examples using chainable setters:

// Specify filter as an object
user.thng()
  .setFilter('name=Pallet*&tags=shipped')
  .read()
  .then(console.log);

// Specify parameters such as project scope on creating a Thng
const projectId = 'UF6HgyNFVDswQKRRwhPK3kCg';
const payload = { name: 'Example Thng' };
user.thng()
  .setProject(projectId)
  .create(payload)
  .then(console.log);

// Read a single Thng with a certain tags pattern with context and scopes
user.action()
  .setPerPage(1)
  .setFilter('tags=batch-*')
  .setWithScopes()
  .setContext()
  .read()
  .then(console.log);