High- and low-level libraries for interacting with the Dispatch API
npm install dispatch-node-sdkDispatch JavaScript SDK
=======================
High- and low-level libraries for interacting with the Dispatch API.
trunk/1.X.X and trunk/2.X.X respectively.#### Version 3.9+
These dependencies are now peer dependencies and must be installed manually:
- crypto-js (formerly used Node's built-in crypto library, this caused a huge overhead when bundling for a web app)
- form-data (upgraded to latest major version)
- isomorphic-fetch (upgraded to latest major version)
- lodash (formerly used underscore, now using only minor parts of lodash)
- moment
- moment-timezone
- uuid (formerly used node-uuid, which is now deprecated)
For example (you may need to install specific versions):
``sh`using npm
npm install --save crypto-js form-data isomorphic-fetch lodash moment moment-timezone uuidor with yarn
yarn add crypto-js form-data isomorphic-fetch lodash moment moment-timezone uuid
The reason for this is to ensure you can more easily upgrade to minor and patch versions for these libraries.
Also removed the simplecheck library as it was only used in one place.
$ npm install --save dispatch-node-sdk
`Usage
Client SDK
The client SDK is meant for use on the browser. It assumes that there is only one active bearer token at a time - for server-level use, please use the raw Client.
$3
Create a new instance of the client with your client_id and client_secret.`javascript
import Dispatch from 'dispatch-node-sdk';
const dispatchClient = new Dispatch(clientID, clientSecret, 'https://api.dispatch.me');
`$3
#### Set the Bearer Token
You can manually set the API bearer token if it came from an external source:`javascript
client.setBearerToken(bearerToken, refreshToken);
`#### Log in with username/password
`javascript
client.loginEmailPassword(email, password).then(() => {
return client.identifyUser();
}).then(user => {
console.log('Current user is', user);
}).catch(err => console.error('Failed to log in:', err));
`#### Log in with phone + verification code
`javascript
client.requestVerificationCode('+15555555555').then(() => {
alert('Verification code will be sent to your phone!');
}).catch(err => alert('Error getting verification code'));// Later...
client.loginPhoneNumber('+15555555555', verificationCode).then(token => {
alert('Got bearer token: ' + token);
}).catch(err => alert('Error logging in!'));
`#### Login with limited-use auth token
`javascript
client.loginAuthToken(token).then(() => {
return client.identifyUser();
}).then(user => {
console.log('Current user is', user);
}).catch(err => console.error('Failed to log in:', err));
`$3
#### Get a list of models
You can use the
getCollection method directly, like this:`javascript
client.getCollection('/v1/jobs', {
filter: {
status_eq: 'unscheduled',
}
}).then(jobs => {
jobs.forEach(job => console.log('Got job ID ' + job.get('id')));
}).catch(err => alert('Error loading jobs!'));
`Or, use the defined collection, like this:
`javascript
client.entities.jobs.get({
filter: {
status_eq: 'unscheduled',
}
});
`You can also get meta data (such as pagination, etc.) using
getCollectionWithMeta:`javascript
client.getCollectionWithMeta('/v1/jobs', {
filter: {
status_eq: 'unscheduled',
}
}).then(response => {
...
})
`
where response has the following structure:`javascript
response: {
data: [...],
meta: {...},
}
`
if there are more then one sources of data returned from the API that are not meta:`javascript
response: {
data: {
source1: [...],
source2: [...],
...
},
meta: {...},
}
`#### Creating a Model
`javascript
client.entities.jobs.create({
title: 'New job!',
}).then(...);
`#### Retrieving a single model
Sometimes you may want to just get a single model instead of an entire collection. For example, to retrieve job #1:
`javascript
client.getModel('/v1/jobs', 1)
.then(job => alert('Job 1 has status: ' + job.status))
.catch(err => alert('Error loading job #1'));
`Similarly:
`javascript
client.entities.jobs.getOne(1).then(...)
`#### Updating a model
Once you have a model, you can modify it and save it:
`javascript
model.status = 'new status';
client.entities.jobs.update(1, model).then(...);
`#### Entity-specific Functions
Some entities have additional abstracted convenience functions. For example:
`javascript
client.entities.job(123).addNote('note text').then(...)
`Entities
$3
Get one customer by id:
`client.entities.customer(:id)`Update one customer by id and properties:
`client.entities.customer(:id).update(: properties)`Get all attachments for a customer by id:
`client.entities.customer(:id).getAttachments()`Auxiliary Services
The Dispatch client has built-in support for interacting with auxiliary Dispatch APIs such as the Files API or Configuration Service. You should not have to use this directly as there are abstracted functions like uploadFile and configuration.getForEntity that make use of it, but if you need to, you can do the following:This will make a POST request to
https://my-service-name.dispatch.me:
`javascript
myClient.getAuxiliaryClient('my-service-name').post('/foo', {body}).then(...);
`This will do the same POST request but also handle automatic token refreshing if necessary:
`javascript
myClient.doAuthenticatedRequest('POST', '/foo', {body}, {
client: 'my-service-name',
}).then(...);
`Raw Client
Use the low-level raw client on the server-side for shared-key authentication:`javascript
import { RawClient, AUTH_MODE_HMAC } from 'dispatch-node-sdk';const client = new RawClient({
authMode: AUTH_MODE_HMAC,
hmacCredentials: {
userID: 10,
userType: 'user',
secret: '',
},
host: 'https://api-sandbox.dispatch.me',
});
client.get('/v1/jobs')
.then(jobs => console.log('Got %d jobs', jobs.jobs.length))
.catch(err => console.error(err));
`Organization-Scope Functions
These functions are available on client.entities.organization(id).
$3
`js
client.entities.organization(5).addCustomer({
first_name: 'Ron',
last_name: 'Swanson',
email: 'rswan@pr.com',
home_address: {
street_1: '2475 Mountain Avenue',
street_2: '',
postal_code: '50265',
city: 'West Des Moines',
state: 'IA',
},
phone_number: '+17069203204',
phone_numbers: {
'+17069203204': {
type: 'Mobile',
number: '+17069203204',
primary: true,
},
},
}).then(result => {
// result is the created customer object returned from the API
});
`$3
Checks whether a date falls during an organization's defined work hours. The organization must have a
timezone defined for this to work. Otherwise it always returns false.`js
const date = new Date();
client.entities.organization(5).dateIsInWorkHours(date).then(result => {
// result is true or false
});
`User-Scope Functions
These functions are available on client.entities.user(id).
$3
Checks whether a date falls during a user's defined work hours, or during that user's organization's defined work hours if the user does not have work hours defined. Either the user or the organization must have a
timezone defined for this to work. Otherwise it always returns false.`js
const date = new Date();
client.entities.user(5).dateIsInWorkHours(date).then(result => {
// result is true or false
});
`Publishing
Once you have commited all your changes and pushed to your respective branch, the steps to publishing to NPM are as follows:
1. Update the package version in
package.json
2. Run npm publish
3. Commit your changes with a comment describing the updated version eg. "Bumped version to 1.2.3"
4. Tag the release with the respective version, eg.
* git tag 1.2.3
* git push origin --tags`