@getcircuit/engine-client

Package for consuming the Circuit Engine API via JavaScript. Failed requests are automatically retried up to 3 times, via p-retry.

Usage no npm install needed!

<script type="module">
  import getcircuitEngineClient from 'https://cdn.skypack.dev/@getcircuit/engine-client';
</script>

README

@getcircuit/engine-client

Package for consuming the Circuit Engine API via JavaScript. Failed requests are automatically retried up to 3 times, via p-retry.

Using

Initializing

First we need to initialize the client with some important information such as:

  • the base url for the Circuit Engine API
  • a method to return the user's token, if using a private API method.
  • some environment variables.
import { createEngineClient } from '@getcircuit/engine-client'

const baseUrl = process.env.FIREBASE_EMULATOR
  ? `http://localhost:3333/rest`
  : process.env.FIREBASE_ENV !== 'production'
  ? `https://staging-api.getcircuit.com/rest`
  : `https://api.getcircuit.com/rest`

// Required
const engineClient = createEngineClient({
  baseUrl,
  // Optional. Only used for private APIs.
  getToken: () => '',
  env: {
    FIREBASE_ENV: 'production' | 'development',
  },
})

Methods

After initializing the client, we're ready to use the methods to our hearts desires.

engineClient.importQueries()
engineClient.createUser()
engineClient.createMember()
engineClient.activateUser()
engineClient.optimizePlan()
engineClient.updateStripeSubscription()
engineClient.searchAddress()
engineClient.geocodeStop()

Contributing

How it works

The createEngineClient method grabs all the exported methods of src/methods/index.ts, all of which receive a context value as their first argument, and binds them to the client's context. Think this as instantiating a new object of a certain class. However, we don' deal with the this reference, as things can get very messy with them. Instead, we create a new object for the context and then create a copy of each method bound to that object.

Simplified example:

function CreateUser(context, { email }) {
  return context.request('/createUser', { json: { email } })
}

const Methods = {
  CreateUser,
}

function createEngineClient() {
  const context = {
    request: () => {},
  }

  return {
    // this binds the first argument to the object referenced by `context`
    CreateUser: CreateUser.bind(undefined, context),
  }
}

// ...

const client = createEngineClient()

client.createUser('foo@bar.com')