Documentation
API Wrapper

This library is for interacting with DADI API and provides a high-level abstraction of the REST architecture style, exposing a set of chainable methods that allow developers to compose complex read and write operations using a simplistic and natural syntax.

Anchor link Getting started

  1. Install the @dadi/api-wrapper module:

    npm install @dadi/api-wrapper
    
  2. Add the library and configure the API settings:

    const DadiAPI = require('@dadi/api-wrapper')
    const api = new DadiAPI({
      uri: 'http://api.example.com',
      port: 80,
      credentials: {
        clientId: 'johndoe',
        secret: 'f00b4r'
      },
      version: '1.0',
      database: 'library'
    })
    
  3. Make a query:

    // Example: getting all documents where `name` contains "john" and age is greater than 18
    api.in('users')
     .whereFieldContains('name', 'john')
     .whereFieldIsGreaterThan('age', 18)
     .find()
     .then(response => {
       // Use documents here
     })
    

Anchor link Model access

When working from within an API file, like a custom JavaScript endpoint or a collection hook, it's possible to make API Wrapper use the API models directly instead of creating an HTTP request.

To enable this, replace the options object passed to the constructor with the Model export of the @dadi/api module.

const DadiAPI = require('@dadi/api-wrapper')
const Model = require('@dadi/api').Model
const api = new DadiAPI(Model)

// Filters and terminators still work exactly in the same way. 
api.in('users')
  .whereFieldContains('name', 'john')
  .whereFieldIsGreaterThan('age', 18)
  .find()
  .then(response => {
    // Use documents here
  })

Anchor link Methods

Each query consists of a series of chained methods to form the request, always containing a terminator method. Terminators return a Promise with the result of one or more requests to the database and can make use of a series of filtering methods to create the desired subset of documents to operate on.

Anchor link Terminators

Anchor link apply

.apply(callback)

Updates a list of documents with the result of individually applying callback to them.

api.in('users')
  .whereFieldExists('gender')
  .apply(document => {
    document.name = (document.gender === 'male') ? (`Mr ${document.name}`) : (`Mrs ${document.name}`)

    return document
  })

Anchor link create

.create()

Creates a document.

// Example
api.in('users')
   .create({
      name: 'John Doe',
      age: 45,
      address: '123 Fake St'
   })
   .then(function (doc) {
      console.log('New document:', doc)
   })
   .catch(function (err) {
      console.log('! Error:', err)
   })

Anchor link delete

.delete()

Deletes one or more documents.

api.in('users')
   .whereFieldDoesNotExist('name')
   .delete()

Anchor link find

.find(options)

Returns a list of documents.

api.in('users')
   .whereFieldIsGreaterThan('age', 21)
   .useFields(['name', 'age'])
   .find(options)

options is one of the following:

Anchor link getCollections

.getCollections()

Gets the list of collections for the API.

api.getCollections()

Anchor link getConfig

.getConfig()

Gets the config for a collection or for the API.

// Gets the collection config
api.in('users')
   .getConfig()
// Gets the API config
api.getConfig()

Anchor link getSignedUrl

.getSignedUrl()

Gets a signed URL from a media collection.

api.in('images')
   .getSignedUrl({
    fileName: "foobar.jpg"
   })

Anchor link getStats

.getStats()

Gets collection stats.

api.in('users')
   .getStats()

Anchor link getStatus

.getStatus()

Gets the the API status.

api.getStatus()

Anchor link update

.update(update)

Updates a list of documents.

api.in('users')
   .whereFieldIsLessThan('age', 18)
   .update({
      adult: false
   })

Anchor link Filters

Filtering methods are used to create a subset of documents that will be affected by subsequent operation terminators.

Anchor link goToPage

.goToPage(page)

Defines the page of documents to be used.

// Example
api.goToPage(3)

Anchor link limitTo

.limitTo(limit)

Defines a maximum number of documents to be retrieved.

// Example
api.limitTo(10)

Anchor link sortBy

.sortBy(field, order)

Selects a field to sort on and the sort direction. Order defaults to ascending (asc).

// Example
api.sortBy('age', 'desc')

Anchor link useFields

.useFields(arrayOfFields)

Selects the fields to be returned in the response. Accepts array format.

// Example
api.useFields(['name', 'age'])

Anchor link where

.where(query)

Filters documents using a MongoDB query object or a Aggregation Pipeline array. The methods below are ultimately just syntatic sugar for where(). The where() method can be used for complex queries that require operations not implemented by any other method.

// Example
api.where({name: 'John Doe'})

Anchor link whereClientIs(value)

Applicable when in "client mode". Selects the client with ID equal to value.

// Example
api.inClients().whereClientIs('testClient')

Anchor link whereClientIsSelf()

Applicable when in "client mode". Selects the client associated with the bearer token being used.

// Example
api.inClients().whereClientIsSelf()

Anchor link whereFieldBeginsWith

.whereFieldBeginsWith(field, text)

Filters documents where field begins with text.

// Example
api.whereFieldBeginsWith('name', 'john')

Anchor link whereFieldContains

.whereFieldContains(field, text)

Filters documents where field contains text.

// Example
api.whereFieldContains('name', 'john')

Anchor link whereFieldDoesNotContain

.whereFieldDoesNotContain(field, text)

Filters documents where field does not contain text.

// Example
api.whereFieldDoesNotContain('name', 'john')

Anchor link whereFieldEndsWith

.whereFieldEndsWith(field, text)

Filters documents where field starts with text.

// Example
api.whereFieldEndsWith('name', 'john')

Anchor link whereFieldExists

.whereFieldExists(field)

Filters documents that contain a field.

// Example
api.whereFieldExists('name')

Anchor link whereFieldDoesNotExist

.whereFieldDoesNotExist(field)

Filters documents that do not contain a field.

// Example
api.whereFieldDoesNotExist('address')

Anchor link whereFieldIsEqualTo

.whereFieldIsEqualTo(field, value)

Filters documents where field is equal to value.

// Example
api.whereFieldIsEqualTo('age', 53)

Anchor link whereFieldIsGreaterThan

.whereFieldIsGreaterThan(field, value)

Filters documents where field is greater than value.

// Example
api.whereFieldIsGreaterThan('age', 18)

Anchor link whereFieldIsGreaterThanOrEqualTo

.whereFieldIsGreaterThanOrEqualTo(field, value)

Filters documents where field is greater than or equal to value.

// Example
api.whereFieldIsGreaterThanOrEqualTo('age', 19)

Anchor link whereFieldIsLessThan

.whereFieldIsLessThan(field, value)

Filters documents where field is less than value.

// Example
api.whereFieldIsLessThan('age', 65)

Anchor link whereFieldIsLessThanOrEqualTo

.whereFieldIsLessThanOrEqualTo(field, value)

Filters documents where field is less than or equal to value.

// Example
api.whereFieldIsLessThanOrEqualTo('age', 64)

Anchor link whereFieldIsOneOf

.whereFieldIsOneOf(field, matches)

Filters documents where the value of field is one of the elements of matches.

// Example
api.whereFieldIsOneOf('name', ['John', 'Jack', 'Peter'])

Anchor link whereFieldIsNotEqualTo

.whereFieldIsNotEqualTo(field, value)

Filters documents where field is not equal to value.

// Example
api.whereFieldIsEqualTo('age', 53)

Anchor link whereFieldIsNotOneOf

.whereFieldIsNotOneOf(field, matches)

Filters documents where the value of field is not one of the elements of matches.

// Example
api.whereFieldIsNotOneOf('name', ['Mark', 'Nathan', 'David'])

Anchor link whereHookNameIs

.whereHookNameIs(name)

Selects the hook with a given name.

// Example
api.whereFieldIsNotOneOf('name', ['Mark', 'Nathan', 'David'])

Anchor link withComposition

.withComposition(value)

Defines whether nested documents should be resolved using composition. The default is to let API decide based on the queried collection's settings.

// Example
api.withComposition()
api.withComposition(true) // same as above
api.withComposition(false)

Anchor link Other methods

Anchor link fromEndpoint

.fromEndpoint(endpoint)

Selects a custom endpoint to use. Please note that unlike collections, custom endpoints do not have a standardised syntax, so it is up to the authors to make sure the endpoint complies with standard DADI API formats, or they will not function as expected.

// Example
api.fromEndpoint('custom-endpoint')

Anchor link in

.in(collection)

Selects the collection to use.

// Example
api.in('users')

Anchor link .inClients()

Selects "client mode", meaning filters and terminators will operate on clients and not on documents.

// Example
api.inClients()

Anchor link inHooks

.inHooks()

Selects "hook mode", meaning filters and terminators will operate on hooks and not on documents.

// Example
api.inMedia('images')

Anchor link inMedia

.inMedia(bucket)

Selects a media bucket to be used.

// Example
api.inMedia('images')

Anchor link useDatabase

.useDatabase(database)

Selects the database to use. Overrides any database defined in the initialisation options, and is reset when called without arguments.

// Example
api.useDatabase('my-database-name')

Anchor link useVersion

.useVersion(version)

Selects the version to use. Overrides any version defined in the initialisation options, and is reset when called without arguments.

// Example
api.useVersion('1.0')