Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@onfleet/node-onfleet

Package Overview
Dependencies
Maintainers
3
Versions
29
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@onfleet/node-onfleet - npm Package Compare versions

Comparing version 1.2.6 to 1.2.7

.github/pull_request_template.md

7

lib/onfleet.js

@@ -30,6 +30,7 @@ const DEFAULT_URL = 'https://onfleet.com';

class Onfleet {
constructor(apiKey, userTimeout, bottleneckOptions) {
constructor(apiKey, userTimeout, bottleneckOptions, baseURL = DEFAULT_URL) {
if (!apiKey) {
throw new ValidationError('Onfleet API key not found, please obtain an API key from your organization admin');
} if (userTimeout > 70000) {
}
if (userTimeout > 70000) {
throw new ValidationError('User-defined timeout has to be shorter than 70000ms');

@@ -39,3 +40,3 @@ } else {

this.api = {
baseUrl: `${DEFAULT_URL}${DEFAULT_PATH}/${DEFAULT_API_VERSION}`,
baseUrl: `${baseURL}${DEFAULT_PATH}/${DEFAULT_API_VERSION}`,
// eslint-disable-next-line no-unneeded-ternary

@@ -42,0 +43,0 @@ timeout: (userTimeout ? userTimeout : DEFAULT_TIMEOUT),

{
"name": "@onfleet/node-onfleet",
"version": "1.2.6",
"description": "Official client library for accessing the Onfleet API",
"version": "1.2.7",
"description": "Onfleet's Node.js API Wrapper Package",
"main": "index.js",

@@ -6,0 +6,0 @@ "scripts": {

# Onfleet Node.js Wrapper
![Travis (.org)](https://img.shields.io/travis/onfleet/node-onfleet.svg?style=popout-square)
[![GitHub](https://img.shields.io/github/license/onfleet/node-onfleet.svg?style=popout-square)](https://github.com/onfleet/node-onfleet/blob/master/LICENSE)
![David](https://img.shields.io/david/onfleet/node-onfleet.svg?style=popout-square)
[![npm (scoped)](https://img.shields.io/npm/v/@onfleet/node-onfleet.svg?style=popout-square)](https://www.npmjs.com/package/@onfleet/node-onfleet)
![GitHub top language](https://img.shields.io/github/languages/top/onfleet/node-onfleet.svg?style=popout-square)
[![npm](https://img.shields.io/npm/dt/@onfleet/node-onfleet.svg?style=popout-square)](https://www.npmjs.com/package/@onfleet/node-onfleet)
![Build](https://img.shields.io/travis/onfleet/node-onfleet.svg?style=popout-square)
[![License](https://img.shields.io/github/license/onfleet/node-onfleet.svg?style=popout-square)](https://github.com/onfleet/node-onfleet/blob/master/LICENSE)
[![Latest version](https://img.shields.io/npm/v/@onfleet/node-onfleet.svg?style=popout-square)](https://www.npmjs.com/package/@onfleet/node-onfleet)
![Top language](https://img.shields.io/github/languages/top/onfleet/node-onfleet.svg?style=popout-square)
![Dependencies](https://img.shields.io/david/onfleet/node-onfleet.svg?style=popout-square)
[![Downloads](https://img.shields.io/npm/dt/@onfleet/node-onfleet.svg?style=popout-square)](https://www.npmjs.com/package/@onfleet/node-onfleet)
*Lisez ce document dans une autre langue: [English](https://github.com/onfleet/node-onfleet/blob/master/README.md), [French](https://github.com/onfleet/node-onfleet/blob/master/README.fr.md), [中文](https://github.com/onfleet/node-onfleet/blob/master/README.zh-tw.md)*
> *Lisez ce document dans une autre langue*:
> [English](https://github.com/onfleet/node-onfleet/blob/master/README.md)
> [正體中文](https://github.com/onfleet/node-onfleet/blob/master/README.zh-tw.md)
> [Español](https://github.com/onfleet/node-onfleet/blob/master/README.es.md)
Visitez notre [article de blog sur le projet de wrapper API](https://onfleet.com/blog/api-wrappers-explained/) pour en savoir plus sur nos initiatives. Si vous avez des questions, veuillez contacter Onfleet en soumettant un problème [ici](https://github.com/onfleet/node-onfleet/issues) ou contactez support@onfleet.com.
Visitez notre article de blog sur le [projet de wrapper API](https://onfleet.com/blog/api-wrappers-explained/) pour en savoir plus sur nos initiatives.
Si vous avez des questions, veuillez contacter Onfleet en soumettant un problème [ici](https://github.com/onfleet/node-onfleet/issues) ou contactez support@onfleet.com.
### Table des matières
- [Onfleet Node.js Wrapper](#onfleet-nodejs-wrapper)
+ [Table des matières](#table-des-matières)
* [Synopsis](#synopsis)
* [Installation](#installation)
* [Utilisation](#utilisation)
+ [Authentification](#authentification)
+ [Tests unitaires](#tests-unitaires)
+ [étranglement](#étranglement)
+ [Réponses](#réponses)
+ [Opérations CRUD prises en charge](#opérations-crud-prises-en-charge)
- [Requêtes GET](#requêtes-get)
* [Exemples de get()](#exemples-de-get)
* [Exemples de get(param)](#exemples-de-get-param)
* [Exemples de getByLocation](#exemples-de-getbylocation)
- [Requêtes POST](#requêtes-post)
* [Exemples de create()](#exemples-de-create)
- [Demandes PUT](#demandes-put)
* [Exemples de update()](#exemples-de-update)
* [Exemples de insertTask()](#exemples-de-inserttask)
- [DELETE Demandes](#delete-demandes)
* [Exemples de deleteOne()](#exemples-de-deleteone)
+ [Exemples d'utilisation de vos opérations CRUD](#exemples-d-utilisation-de-vos-opérations-crud)
+ [Choses à ne pas faire](#choses-à-ne-pas-faire)
* [Table des matières](#table-des-matières)
* [Synopsis](#synopsis)
* [Installation](#installation)
* [Utilisation](#utilisation)
* [Authentification](#authentification)
* [Tests unitaires](#tests-unitaires)
* [Étranglement](#étranglement)
* [Réponses](#Réponses)
* [Opérations CRUD prises en charge](#opérations-crud-prises-en-charge)
- [Demandes GET](#demandes-get)
* [Exemples de `get()`](#exemples-de-get)
* [Exemples de `get(param)`](#exemples-de-getparam)
* [Exemples de `getByLocation`](#exemples-de-getbylocation)
- [Demandes POST](#demandes-post)
* [Exemples de `create()`](#exemples-de-create)
- [Demandes PUT](#demandes-put)
* [Exemples de `update()`](#exemples-de-update)
* [Exemples de `insertTask()`](#exemples-de-inserttask)
- [Demandes DELETE](#demandes-delete)
* [Exemples de `deleteOne()`](#exemples-de-deleteone)
* [Exemples d'utilisation de vos opérations CRUD](#exemples-dutilisation-de-vos-opérations-crud)
* [Choses à ne pas faire](#choses-à-ne-pas-faire)
## Synopsis
La bibliothèque Onfleet Node.js offre un accès pratique à l'API Onfleet.
## Installation
```
npm install @onfleet/node-onfleet
```
Pour TypeScript, installez la [typed definition](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/onfleet__node-onfleet):
```
npm install @types/onfleet__node-onfleet
```
> Bravo à @marcobeltempo pour la contribution!
(Bravo à @marcobeltempo pour la contribution!)
## Utilisation
Avant d'utiliser le wrapper de l'API, vous devez vous procurer une clé API auprès de votre administrateur d'organisation. La création et l'intégration des clés API sont effectuées via le [tableau de bord Onfleet](https://onfleet.com/dashboard#/manage).
Avant d'utiliser le wrapper de l'API, vous devez vous procurer une clé API auprès de votre administrateur d'organisation.
Pour commencer à utiliser l'API Onfleet, il vous suffit de créer un objet Onfleet avec votre clé API:
La création et l'intégration des clés API sont effectuées via le [tableau de bord Onfleet](https://onfleet.com/dashboard#/manage).
Pour commencer à utiliser l'API Onfleet, il vous suffit de créer un objet `Onfleet` avec votre clé API:
```js
const onfleet = new Onfleet('<clé_api>');
const onfleetApi = new Onfleet("<your_api_key>");
```
En tant que champ facultatif, vous pouvez introduire un délai d'expiration personnalisé inférieur à la valeur par défaut de 70000 ms (délai d'expiration de l'API Onfleet par défaut) en fournissant un 2ème paramètre:
```js
const onfleet = new Onfleet('<clé_api>', 30000) // Cela mettra vos wrappers à expiration à 30000ms au lieu de 70000ms
const onfleetApi = new Onfleet("<your_api_key>", 30000);
```
En tant que champ facultatif, vous pouvez introduire un objet d'options pour [Bottleneck](https://www.npmjs.com/package/bottleneck).
```js
const onfleet = new Onfleet("<api_key>", 30000, {
LIMITER_RESERVOIR: 10, // default 20
LIMITER_WAIT_UPON_DEPLETION: 20000, // default 10000
LIMITER_MAX_CONCURRENT: 5, // default 1
LIMITER_MIN_TIME: 50, // default 50
const onfleetApi = new Onfleet("<your_api_key>", 30000, {
LIMITER_RESERVOIR: 10, // Default: 20
LIMITER_WAIT_UPON_DEPLETION: 20000, // Default: 10000
LIMITER_MAX_CONCURRENT: 5, // Default: 1
LIMITER_MIN_TIME: 50, // Default: 50
});

@@ -81,5 +82,5 @@ ```

### Authentification
Une fois que l'objet Onfleet est créé, vous pouvez utiliser une fonction utilitaire pour tester le noeud final d'authentification. Cette fonction renvoie un booléen:
Une fois que l'objet `Onfleet` est créé, vous pouvez tester le noeud final d'authentification:
```js
onfleet.verifyKey();
onfleet.verifyKey(); // Returns a boolean
```

@@ -90,15 +91,17 @@

### Tests unitaires
Exécuter `npm test`
`npm test`
### étranglement
La limitation de débit est appliquée par l'API avec un seuil de 20 demandes par seconde pour toutes les clés d'API de votre organisation. Pour en savoir plus, [cliquez ici](https://docs.onfleet.com/reference#throttling). Nous avons mis en place un limiteur sur le wrapper lui-même pour vous éviter de dépasser involontairement vos limitations de taux et éventuellement être banni.
### Étranglement
La limitation de débit est appliquée par l'API avec un seuil de 20 demandes par seconde pour toutes les clés d'API de votre organisation. Pour en savoir plus, [cliquez ici](https://docs.onfleet.com/reference#throttling).
Nous avons mis en place un limiteur sur le wrapper lui-même pour vous éviter de dépasser involontairement vos limitations de taux et éventuellement être banni.
### Réponses
Le wrapper de l'API `node-onfleet` renvoie le `body` d'un [objet Response](https://developer.mozilla.org/en-US/docs/Web/API/Response).
La bibliothèque renvoie le _body_ d'un objet [Response](https://developer.mozilla.org/en-US/docs/Web/API/Response).
### Opérations CRUD prises en charge
L'URL de base de l'API Onfleet est `https://onfleet.com/api/v2`, voici les opérations CRUD prises en charge pour chaque ordinateur d'extrémité:
Voici les opérations CRUD prises en charge pour chaque ordinateur d'extrémité:
| `<endpoint>` | GET | POST | PUT | DELETE |
|:------------:|:---------------------------------------------------:|:----------------------------------------------------------------------:|:------------------------------------:|:-------------:|
| Entity | GET | POST | PUT | DELETE |
| :-: | :-: | :-: | :-: | :-: |
| [Admins/Administrators](https://docs.onfleet.com/reference#administrators) | get() | create(obj), matchMetadata(obj) | update(id, obj) | deleteOne(id) |

@@ -115,126 +118,107 @@ | [Containers](https://docs.onfleet.com/reference#containers) | get(id, 'workers'), get(id, 'teams'), get(id, 'organizations') | x | update(id, obj) | x |

#### Requêtes GET
Pour obtenir tous les documents d'un noeud final, cela renvoie une promesse contenant un tableau de résultats:
#### Demandes GET
Pour obtenir tous les documents d'un noeud final, cela renvoie une `Promise` contenant un tableau de résultats:
```js
get();
get(<queryParam> (facultatif));
```
##### Exemples de get()
##### Exemples de `get()`
```js
onfleet.workers.get().then((resultArray) => {
    // faire quelque chose avec le tableau contenant tous les ouvriers
});
onfleetApi.workers.get().then((results) => { /* ... */ });
onfleetApi.workers.get({ queryParams }).then((results) => { /* ... */ });
```
Option permettant d'utiliser des paramètres de requête pour certains points de terminaison, reportez-vous aux documents de l'API pour les points de terminaison prenant en charge les paramètres de requête:
Option permettant d'utiliser des paramètres de requête pour certains points de terminaison, reportez-vous aux [documents de l'API](https://docs.onfleet.com/) pour les points de terminaison prenant en charge les paramètres de requête.
```js
onfleet.workers.get({phones: '<phone_number>'}).then((res) => {
  // faire quelque chose avec le résultat trouvé
});
onfleet.tasks.get({from: '<from_time>', to: '<to_time>'}).then((result) => {
// faire quelque chose avec le résultat trouvé
});
onfleetApi.workers.get({ phones: "<phone_number>" }).then((results) => { /* ... */ });
onfleetApi.tasks.get({ from: "<from_time>", to: "<to_time>" }).then((results) => { /* ... */ });
```
> **Remarque:** Les paramètres de requête peuvent figurer dans n’importe quel formulaire, à condition qu’il s’agisse d’un objet JSON, par exemple: `{ analytics: true }` et `{ 'analytics': 'true' }` sont identiques.
Pour obtenir l'un des documents dans un noeud final, si *paramName* facultatif n'est pas fourni, l'encapsuleur effectuera une recherche par ID. Si *paramName* est fourni, il recherchera par * paramName *:
> Les paramètres de requête peuvent figurer dans n’importe quel formulaire, à condition qu’il s’agisse d’un objet JSON, par exemple: `{ analytics: true }` et `{ 'analytics': 'true' }` sont identiques
Pour obtenir l'un des documents dans un noeud final, si _paramName_ facultatif n'est pas fourni, l'encapsuleur effectuera une recherche par ID. Si _paramName_ est fourni, il recherchera par _paramName_:
```js
get(<paramètre>, <nomParam>(facultatif), <queryParam>(facultatif));
get(<parameter>, <paramName> (optional), <queryParam> (optional));
```
Options pour *paramName*: delegateeId, name, phone, shortId et coordinates (voir tableau ci-dessus).
##### Exemples de get(param)
Options pour _paramName_:
- `id`
- `name`
- `phone`
- `shortId`
##### Exemples de `get(param)`
```js
/**
* Workers
*/
onfleet.workers.get('<24_digit_id>').then((result)) => {
  // faire quelque chose avec le résultat trouvé
});
onfleet.workers.get('<24_digit_id>', { analytics: true }).then((result) => {
  // faire quelque chose avec le résultat trouvé
});
onfleetApi.workers.get("<24_digit_ID>").then((result) => { /* ... */ });
onfleetApi.workers.get("<24_digit_ID>", { analytics: true }).then((result) => { /* ... */ });
/**
* Tasks
*/
onfleet.tasks.get('<shortId>', 'shortId').then((result)) => {
  // faire quelque chose avec le résultat trouvé
});
onfleetApi.tasks.get("<shortId>", "shortId").then((result) => { /* ... */ });
/**
* Recipients
*/
onfleet.recipients.get('<numéro_phone>', 'phone').then((result)) => {
  // faire quelque chose avec le résultat trouvé
});
onfleet.recipients.get('<destinataire_nom>', 'name').then((result)) => {
  // faire quelque chose avec le résultat trouvé
});
onfleet.recipients.get('<<destinataire_nom>', 'name', {skipPhoneNumberValidation: true}).then((result)) => {
  // faire quelque chose avec le résultat trouvé
});
onfleetApi.recipients.get("<phone_number>", "phone").then((result) => { /* ... */ });
onfleetApi.recipients.get("<recipient_name>", "name").then((result) => { /* ... */ });
onfleetApi.recipients
.get("<recipient_name>", "name", { skipPhoneNumberValidation: true })
.then((result) => { /* ... */ });
/**
* Containers
*/
onfleet.containers.get('<24_digit_id>', 'workers').then((result) => {
// faire quelque chose avec le résultat trouvé
});
onfleet.containers.get('<24_digit_id>', 'teams').then((result) => {
// faire quelque chose avec le résultat trouvé
});
onfleet.containers.get('<24_digit_id>', 'organizations').then((result) => {
// faire quelque chose avec le résultat trouvé
});
onfleetApi.containers.get("<24_digit_ID>", "workers").then((result) => { /* ... */ });
onfleetApi.containers.get("<24_digit_ID>", "teams").then((result) => {{ /* ... */ });
onfleetApi.containers.get("<24_digit_ID>", "organizations").then((result) => { /* ... */ });
```
Pour obtenir un pilote par emplacement, utilisez la fonction `getByLocation`:
```js
getByLocation(<queryParam>);
getByLocation({ queryParams });
```
##### Exemples de getByLocation
##### Exemples de `getByLocation`
```js
const location = {
  longitude: -122.404,
  latitude: 37,789,
radius: 10000
}
const locationParams = {
longitude: -122.404,
latitude: 37.789,
radius: 10000,
};
onfleet.workers.getByLocation(location).then((result)) => {
  // montre le travailleur en service à l'emplacement spécifique
});
onfleetApi.workers.getByLocation(locationParams).then((results) => { /* ... */ });
```
#### Requêtes POST
#### Demandes POST
Pour créer un document dans un noeud final:
```js
create(<object>);
create({ data }});
```
##### Exemples de create()
##### Exemples de `create()`
```js
const driver = {
name: 'A Swartz',
phone: '617-342-8853',
teams: ['W*8bF5jY11Rk05E0bXBHiGg2'],
const data = {
name: "John Driver",
phone: "+16173428853",
teams: ["<team_ID>", "<team_ID> (optional)", ...],
vehicle: {
type: 'CAR',
description: 'Tesla Model 3',
licensePlate: 'FKNS9A',
color: 'purple',
type: "CAR",
description: "Tesla Model 3",
licensePlate: "FKNS9A",
color: "purple",
},
};
onfleet.workers.create(driver);
onfleetApi.workers.create(data);
```
Les requêtes POST étendues incluent `clone`,` forceComplete`, `batchCreate`,` autoAssign`, `setSchedule`, `autoDispatch`:
```js
onfleet.tasks.clone('<24_digit_id>');
onfleet.tasks.forceComplete('<24_digit_id>', '<completion_details>');
onfleet.tasks.batchCreate('<task_object_array>');
onfleet.tasks.autoAssign('<auto_assign_object>');
onfleetApi.tasks.clone('<24_digit_ID>');
onfleetApi.tasks.forceComplete('<24_digit_ID>', { data });
onfleetApi.tasks.batchCreate({ data });
onfleetApi.tasks.autoAssign({ data });
onfleet.<entity>.matchMetadata('<metadata_object_array>');
onfleet.workers.setSchedule('<24_digit_id>', newSchedule);
onfleetApi.workers.setSchedule('<24_digit_ID>', { data });
onfleet.teams.autoDispatch('<24_digit_id>', dispatchConfig);
onfleetApi.teams.autoDispatch('<24_digit_ID>', { data });
onfleetApi.<entity_name_pluralized>.matchMetdata({ data });
```
Pour plus de détails, consultez notre documentation sur [clone](https://docs.onfleet.com/reference#clone-task), [forceComplete](https://docs.onfleet.com/reference#complete-task), [batchCreate](https://docs.onfleet.com/reference#create-tasks-in-batch), [autoAssign](https://docs.onfleet.com/reference#automatically-assign-list-of-tasks), [setSchedule](https://docs.onfleet.com/reference#set-workers-schedule), [matchMetadata](https://docs.onfleet.com/reference#querying-by-metadata), et [autoDispatch](https://docs.onfleet.com/reference#team-auto-dispatch).
Pour plus de détails, consultez notre documentation sur [`clone`](https://docs.onfleet.com/reference#clone-task), [`forceComplete`](https://docs.onfleet.com/reference#complete-task), [`batchCreate`](https://docs.onfleet.com/reference#create-tasks-in-batch), [`autoAssign`](https://docs.onfleet.com/reference#automatically-assign-list-of-tasks), [`setSchedule`](https://docs.onfleet.com/reference#set-workers-schedule), [`matchMetadata`](https://docs.onfleet.com/reference#querying-by-metadata), et [`autoDispatch`](https://docs.onfleet.com/reference#team-auto-dispatch).

@@ -244,69 +228,88 @@ #### Demandes PUT

```js
update(<id>, <objet>);
update("<24_digit_ID>", { data });
```
##### Exemples de update()
##### Exemples de `update()`
```js
const updateBody = {
name: 'New Driver Name',
const newData = {
name: "Jack Driver",
};
onfleet.workers.update('<24_digit_id>', updateBody);
onfleetApi.workers.update("<24_digit_ID>", newData);
```
##### Exemples de insertTask()
##### Exemples de `insertTask()`
```js
onfleet.workers.insertTask('kAQ*G5hnqlOq4jVvwtGNuacl', insertedTask).then(result => {
// faire quelque chose avec le résultat trouvé
});
onfleetApi.workers.insertTask("<24_digit_ID>", { data }).then((result) => { /* ... */ });
```
#### DELETE Demandes
#### Demandes DELETE
Pour supprimer un document dans un noeud final:
```js
deleteOne(<id>);
deleteOne("<24_digit_ID>");
```
##### Exemples de deleteOne()
##### Exemples de `deleteOne()`
```js
onfleet.workers.deleteOne('<24_digit_id>');
onfleetApi.workers.deleteOne("<24_digit_ID>");
```
### Exemples d'utilisation de vos opérations CRUD
Obtenez tous les destinataires (s'il existe):
```js
onfleet.tasks.get({from:'1557936000000', to:'1558022400000'}).then((res) => {
for (let element of res) {
if (element.recipients[0] !== undefined) {
// do something with the recipients
- Obtenez tous les destinataires:
```js
onfleetApi.tasks
.get({ from: "1557936000000", to: "1558022400000" })
.then((tasks) => {
for (let task of tasks) {
if (task.recipients[0] !== undefined) {
// Do something with the recipients
}
}
})
.catch((err) => { /* ... */ });
```
- `async`/`await` peut également être utilisé dans les cas suivants:
```js
async function findAllWorkers() {
try {
let response = await onfleetApi.workers.get();
// Do something with the response
}
catch (err) { /* ... */ }
}
}).catch((err) => {
// do something with the error
});
```
Async / wait peut également être utilisé dans les cas suivants:
```js
async function findAllWorkers() {
try {
let response = await onfleet.workers.get();
// do something with the response
} catch(err) {
throw new Error(err);
}
};
findAllWorkers();
```
findAllWorkers();
```
### Choses à ne pas faire
Modèle inefficace, utilisez plutôt des métadonnées:
```js
onfleet.workers.get().then((res) => {
for (let element of res) {
if (element.name == 'some_name') {
onfleet.teams.get(element.teams[0]).then((result) => {
// do something with the team
})
}
}
}).catch((err) => {
// do something with the error
});
```
- Modèle inefficace, utilisez plutôt des métadonnées:
```js
// DONT
onfleetApi.workers
.get()
.then((workers) => {
for (let worker of workers) {
for (let metadataEntry of worker.metadata) {
if (metadataEntry.name === "hasFreezer" && metadataEntry.value) {
// Do something
}
}
}
})
.catch((err) => { /* ... */ });
// DO
onfleetApi.workers
.matchMetadata([{"name": "hasFreezer", "type": "boolean", "value": true}])
.then((workers) => {
for (let worker of workers) {
// Do something
}
})
.catch((err) => { /* ... */ });
```
*Haut de [page](#onfleet-nodejs-wrapper)*.
# Onfleet Node.js Wrapper
![Travis (.org)](https://img.shields.io/travis/onfleet/node-onfleet.svg?style=popout-square)
[![GitHub](https://img.shields.io/github/license/onfleet/node-onfleet.svg?style=popout-square)](https://github.com/onfleet/node-onfleet/blob/master/LICENSE)
![David](https://img.shields.io/david/onfleet/node-onfleet.svg?style=popout-square)
[![npm (scoped)](https://img.shields.io/npm/v/@onfleet/node-onfleet.svg?style=popout-square)](https://www.npmjs.com/package/@onfleet/node-onfleet)
![GitHub top language](https://img.shields.io/github/languages/top/onfleet/node-onfleet.svg?style=popout-square)
[![npm](https://img.shields.io/npm/dt/@onfleet/node-onfleet.svg?style=popout-square)](https://www.npmjs.com/package/@onfleet/node-onfleet)
![Build](https://img.shields.io/travis/onfleet/node-onfleet.svg?style=popout-square)
[![License](https://img.shields.io/github/license/onfleet/node-onfleet.svg?style=popout-square)](https://github.com/onfleet/node-onfleet/blob/master/LICENSE)
[![Latest version](https://img.shields.io/npm/v/@onfleet/node-onfleet.svg?style=popout-square)](https://www.npmjs.com/package/@onfleet/node-onfleet)
![Top language](https://img.shields.io/github/languages/top/onfleet/node-onfleet.svg?style=popout-square)
![Dependencies](https://img.shields.io/david/onfleet/node-onfleet.svg?style=popout-square)
[![Downloads](https://img.shields.io/npm/dt/@onfleet/node-onfleet.svg?style=popout-square)](https://www.npmjs.com/package/@onfleet/node-onfleet)
_Read this document in another language: [English](https://github.com/onfleet/node-onfleet/blob/master/README.md), [French](https://github.com/onfleet/node-onfleet/blob/master/README.fr.md), [正體中文](https://github.com/onfleet/node-onfleet/blob/master/README.zh-tw.md)_
> *Read this document in another language*:
> [Français](https://github.com/onfleet/node-onfleet/blob/master/README.fr.md)
> [正體中文](https://github.com/onfleet/node-onfleet/blob/master/README.zh-tw.md)
> [Español](https://github.com/onfleet/node-onfleet/blob/master/README.es.md)
Visit our [blog post on the API wrapper project](https://onfleet.com/blog/api-wrappers-explained/) to learn more about our initiatives. If you have any questions, please reach out to Onfleet by submitting an issue [here](https://github.com/onfleet/node-onfleet/issues) or contact support@onfleet.com
Visit our blog post on the [API wrapper project](https://onfleet.com/blog/api-wrappers-explained/) to learn more about our initiatives.
If you have any questions, please reach us by submitting an issue [here](https://github.com/onfleet/node-onfleet/issues) or contact support@onfleet.com.
### Table of Contents
- [Onfleet Node.js Wrapper](#onfleet-nodejs-wrapper)
- [Table of Contents](#table-of-contents)
* [Synopsis](#synopsis)
* [Installation](#installation)
* [Usage](#usage)
### Table of contents
* [Table of contents](#table-of-contents)
* [Synopsis](#synopsis)
* [Installation](#installation)
* [Usage](#usage)
- [Authentication](#authentication)
- [Unit Testing](#unit-testing)
- [Unit testing](#unit-testing)
- [Throttling](#throttling)
- [Responses](#responses)
- [Supported CRUD Operations](#supported-crud-operations)
- [GET Requests](#get-requests)
- [Examples of get()](#examples-of-get)
- [Examples of get(param)](#examples-of-get-param)
- [Examples of getByLocation](#examples-of-getbylocation)
- [POST Requests](#post-requests)
- [Examples of create()](#examples-of-create)
- [PUT Requests](#put-requests)
- [Examples of update()](#examples-of-update)
- [Examples of insertTask()](#examples-of-inserttask)
- [DELETE Requests](#delete-requests)
- [Examples of deleteOne()](#examples-of-deleteone)
- [Supported CRUD operations](#supported-crud-operations)
* [GET Requests](#get-requests)
- [Examples of `get()`](#examples-of-get)
- [Examples of `get(param)`](#examples-of-getparam)
- [Examples of `getByLocation`](#examples-of-getbylocation)
* [POST Requests](#post-requests)
- [Examples of `create()`](#examples-of-create)
* [PUT Requests](#put-requests)
- [Examples of `update()`](#examples-of-update)
- [Examples of `insertTask()`](#examples-of-inserttask)
* [DELETE Requests](#delete-requests)
- [Examples of `deleteOne()`](#examples-of-deleteone)
- [Examples of utilizing your CRUD operations](#examples-of-utilizing-your-crud-operations)

@@ -41,43 +43,36 @@ - [Things NOT to do](#things-not-to-do)

## Synopsis
The Onfleet Node.js library provides convenient access to the Onfleet API.
## Installation
```
npm install @onfleet/node-onfleet
```
For TypeScript, install the [typed definition](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/onfleet__node-onfleet):
```
npm install @types/onfleet__node-onfleet
```
> Kudos to @marcobeltempo for the contribution!
(Kudos to @marcobeltempo for the contribution!)
## Usage
Before using the API wrapper, you will need to obtain an API key from one of your organization's admins.
Before using the API wrapper, you will need to obtain an API key from your organization admin. Creation and integration of API keys are performed through the [Onfleet dashboard](https://onfleet.com/dashboard#/manage).
Creation and integration of API keys are performed through the [Onfleet dashboard](https://onfleet.com/dashboard#/manage).
To start utilizing the Onfleet API, you simply need to create an Onfleet object with your API key:
To start utilizing the library, you simply need to create an `Onfleet` object with your API key:
```js
const onfleet = new Onfleet("<api_key>");
const onfleetApi = new Onfleet("<your_api_key>");
```
As an optional field, you can introduce a customized timeout that is less than the default 70000ms (default Onfleet API timeout) by providing a 2nd parameter:
Optionally, you can introduce a customized timeout that is less than the default Onfleet API timeout (70,000 ms) by providing a 2nd parameter:
```js
const onfleet = new Onfleet("<api_key>", 30000); // This will set your wrappers to timeout at 30000ms instead of 70000ms
const onfleetApi = new Onfleet("<your_api_key>", 30000);
```
As an optional field, you can introduce an options object for [Bottleneck](https://www.npmjs.com/package/bottleneck).
Optionally again, you can introduce an options object for [Bottleneck](https://www.npmjs.com/package/bottleneck) as a 3rd parameter:
```js
const onfleet = new Onfleet("<api_key>", 30000, {
LIMITER_RESERVOIR: 10, // default 20
LIMITER_WAIT_UPON_DEPLETION: 20000, // default 10000
LIMITER_MAX_CONCURRENT: 5, // default 1
LIMITER_MIN_TIME: 50, // default 50
const onfleetApi = new Onfleet("<your_api_key>", 30000, {
LIMITER_RESERVOIR: 10, // Default: 20
LIMITER_WAIT_UPON_DEPLETION: 20000, // Default: 10000
LIMITER_MAX_CONCURRENT: 5, // Default: 1
LIMITER_MIN_TIME: 50, // Default: 50
});

@@ -87,72 +82,57 @@ ```

### Authentication
Once the Onfleet object is created, you can use a utility function to test on the authentication endpoint, this function returns a boolean:
Once the `Onfleet` object is created, you can test on the authentication endpoint:
```js
onfleet.verifyKey();
onfleetApi.verifyKey(); // Returns a boolean
```
Once the Onfleet object is created, you will get access to all the API endpoints as documented in the [Onfleet API documentation](https://docs.onfleet.com/). Here are some usage case:
### Unit Testing
`npm test`
Run `npm test`
### Throttling
Rate limiting is enforced by the API with a threshold of 20 requests per second across all your organization's API keys. Learn more about it [here](https://docs.onfleet.com/reference#throttling).
Rate limiting is enforced by the API with a threshold of 20 requests per second across all your organization's API keys, learn more about it [here](https://docs.onfleet.com/reference#throttling). We have implemented a limiter on the wrapper itself to avoid you from unintentionally exceeding your rate limitations and eventually be banned for.
We have also implemented a limiter on this library to avoid you from unintentionally exceeding your rate limitations and eventually be banned for.
### Responses
Responses of this library are instances of [Response](https://developer.mozilla.org/en-US/docs/Web/API/Response).
The `node-onfleet` API wrapper returns the body of a [Response object](https://developer.mozilla.org/en-US/docs/Web/API/Response).
### Supported CRUD Operations
Here are the operations available for each entity:
The base URL for the Onfleet API is `https://onfleet.com/api/v2`, here are the supported CRUD operations for each endpoint:
| Entity | GET | POST | PUT | DELETE |
| :-: | :-: | :-: | :-: | :-: |
| [Admins/Administrators](https://docs.onfleet.com/reference#administrators) | get() | create(obj), matchMetadata(obj) | update(id, obj) | deleteOne(id) |
| [Containers](https://docs.onfleet.com/reference#containers) | get(id, 'workers'), get(id, 'teams'), get(id, 'organizations') | x | update(id, obj) | x |
| [Destinations](https://docs.onfleet.com/reference#destinations) | get(id) | create(obj), matchMetadata(obj) | x | x |
| [Hubs](https://docs.onfleet.com/reference#hubs) | get() | create(obj) | update(id, obj) | x |
| [Organization](https://docs.onfleet.com/reference#organizations) | get(), get(id) | x | insertTask(id, obj) | x |
| [Recipients](https://docs.onfleet.com/reference#recipients) | get(id), get(name, 'name'), get(phone, 'phone') | create(obj), matchMetadata(obj) | update(id, obj) | x |
| [Tasks](https://docs.onfleet.com/reference#tasks) | get(query), get(id), get(shortId, 'shortId') | create(obj), clone(id), forceComplete(id), batch(obj), autoAssign(obj), matchMetadata(obj) | update(id, obj) | deleteOne(id) |
| [Teams](https://docs.onfleet.com/reference#teams) | get(), get(id), getWorkerEta(id, obj) | create(obj), autoDispatch(id, obj) | update(id, obj), insertTask(id, obj) | deleteOne(id) |
| [Webhooks](https://docs.onfleet.com/reference#webhooks) | get() | create(obj) | x | deleteOne(id) |
| [Workers](https://docs.onfleet.com/reference#workers) | get(), get(query), get(id), getByLocation(obj), getSchedule(id) | create(obj), setSchedule(id, obj), matchMetadata(obj) | update(id, obj), insertTask(id, obj) | deleteOne(id) |
| `<endpoint>` | GET | POST | PUT | DELETE |
| :------------------------------------------------------------------------: | :-------------------------------------------------------------: | :----------------------------------------------------------------------------------------: | :----------------------------------: | :-----------: |
| [Admins/Administrators](https://docs.onfleet.com/reference#administrators) | get() | create(obj), matchMetadata(obj) | update(id, obj) | deleteOne(id) |
| [Containers](https://docs.onfleet.com/reference#containers) | get(id, 'workers'), get(id, 'teams'), get(id, 'organizations') | x | update(id, obj) | x |
| [Destinations](https://docs.onfleet.com/reference#destinations) | get(id) | create(obj), matchMetadata(obj) | x | x |
| [Hubs](https://docs.onfleet.com/reference#hubs) | get() | create(obj) | update(id, obj) | x |
| [Organization](https://docs.onfleet.com/reference#organizations) | get(), get(id) | x | insertTask(id, obj) | x |
| [Recipients](https://docs.onfleet.com/reference#recipients) | get(id), get(name, 'name'), get(phone, 'phone') | create(obj), matchMetadata(obj) | update(id, obj) | x |
| [Tasks](https://docs.onfleet.com/reference#tasks) | get(query), get(id), get(shortId, 'shortId') | create(obj), clone(id), forceComplete(id), batch(obj), autoAssign(obj), matchMetadata(obj) | update(id, obj) | deleteOne(id) |
| [Teams](https://docs.onfleet.com/reference#teams) | get(), get(id), getWorkerEta(id, obj) | create(obj), autoDispatch(id, obj) | update(id, obj), insertTask(id, obj) | deleteOne(id) |
| [Webhooks](https://docs.onfleet.com/reference#webhooks) | get() | create(obj) | x | deleteOne(id) |
| [Workers](https://docs.onfleet.com/reference#workers) | get(), get(query), get(id), getByLocation(obj), getSchedule(id) | create(obj), setSchedule(id, obj), matchMetadata(obj) | update(id, obj), insertTask(id, obj) | deleteOne(id) |
#### GET Requests
To get all the documents within an endpoint, this returns a Promise containing an array of results:
To get all the documents within an endpoint, this returns a `Promise` containing an array of results:
```js
get();
get(<queryParam> (optional));
```
##### Examples of get()
##### Examples of `get()`
```js
onfleet.workers.get().then((resultArray) => {
// do something with the array containing all workers
});
onfleetApi.workers.get().then((results) => { /* ... */ });
onfleetApi.workers.get({ queryParams }).then((results) => { /* ... */ });
```
Option to use query parameters for some certain endpoints, refer back to API documents for endpoints that support query parameters:
Optionally you can send a JSON object of query params for some certain endpoints.
Refer back to [API documentation](https://docs.onfleet.com/) for endpoints that support query parameters.
```js
onfleetApi.workers.get({ phones: "<phone_number>" }).then((results) => { /* ... */ });
```js
onfleet.workers.get({ phones: "<phone_number>" }).then((res) => {
// do something with the one result found
});
onfleet.tasks.get({ from: "<from_time>", to: "<to_time>" }).then((result) => {
// do something with the results found
});
onfleetApi.tasks.get({ from: "<from_time>", to: "<to_time>" }).then((results) => { /* ... */ });
```
> **Note:** Query parameters can be in any forms as long as it is a JSON object, for example: `{ 'analytics': 'true' }` works, so as `{ analytics: true }`
> Both `{ 'analytics': 'true' }` and `{ analytics: true }` work as query params since they represent a valid JSON object
To get one of the document within an endpoint, if optional _paramName_ is not provided, wrapper will search by ID. If _paramName_ is provided, it will search by _paramName_:
To get one of the documents within an endpoint, if the optional _paramName_ is not provided, the library will search by ID. If _paramName_ is provided, it will search by _paramName_:
```js

@@ -162,63 +142,34 @@ get(<parameter>, <paramName> (optional), <queryParam> (optional));

Options for _paramName_: id, name, phone, shortId (see table above).
_paramName_ can be any of:
- `id`
- `name`
- `phone`
- `shortId`
##### Examples of get(param)
##### Examples of `get(param)`
```js
/**
* GET for Workers
*/
onfleet.workers.get("<24_digit_id>").then((result) => {
// do something with the one result found
});
onfleet.workers.get("<24_digit_id>", { analytics: true }).then((result) => {
// do something with the one result found
});
onfleetApi.workers.get("<24_digit_ID>").then((result) => { /* ... */ });
onfleetApi.workers.get("<24_digit_ID>", { analytics: true }).then((result) => { /* ... */ });
/**
* GET for Tasks
*/
onfleet.tasks.get("<shortId>", "shortId").then((result) => {
// do something with the one result found
});
onfleetApi.tasks.get("<shortId>", "shortId").then((result) => { /* ... */ });
/**
* GET for Recipients
*/
onfleet.recipients.get("<phone_number>", "phone").then((result) => {
// do something with the one result found
});
onfleet.recipients.get("<recipient_name>", "name").then((result) => {
// do something with the one result found
});
onfleet.recipients
onfleetApi.recipients.get("<phone_number>", "phone").then((result) => { /* ... */ });
onfleetApi.recipients.get("<recipient_name>", "name").then((result) => { /* ... */ });
onfleetApi.recipients
.get("<recipient_name>", "name", { skipPhoneNumberValidation: true })
.then((result) => {
// do something with the one result found
});
.then((result) => { /* ... */ });
/**
* GET for Containers
*/
onfleet.containers.get("<24_digit_id>", "workers").then((result) => {
// do something with the one result found
});
onfleet.containers.get("<24_digit_id>", "teams").then((result) => {
// do something with the one result found
});
onfleet.containers.get("<24_digit_id>", "organizations").then((result) => {
// do something with the one result found
});
onfleetApi.containers.get("<24_digit_ID>", "workers").then((result) => { /* ... */ });
onfleetApi.containers.get("<24_digit_ID>", "teams").then((result) => {{ /* ... */ });
onfleetApi.containers.get("<24_digit_ID>", "organizations").then((result) => { /* ... */ });
```
To get a driver by location, use the `getByLocation` function:
```js
getByLocation(<queryParam>);
getByLocation({ queryParams });
```
##### Examples of getByLocation
##### Examples of `getByLocation`
```js
const location = {
const locationParams = {
longitude: -122.404,

@@ -229,22 +180,17 @@ latitude: 37.789,

onfleet.workers.getByLocation(location).then((result) => {
// shows the on-duty workers at the specific location
});
onfleetApi.workers.getByLocation(locationParams).then((results) => { /* ... */ });
```
#### POST Requests
To create a document within an endpoint:
```js
create(<object>);
```js{
create({ data }});
```
##### Examples of create()
##### Examples of `create()`
```js
const driver = {
name: "A Swartz",
phone: "617-342-8853",
teams: ["W*8bF5jY11Rk05E0bXBHiGg2"],
const data = {
name: "John Driver",
phone: "+16173428853",
teams: ["<team_ID>", "<team_ID> (optional)", ...],
vehicle: {

@@ -257,60 +203,52 @@ type: "CAR",

};
onfleet.workers.create(driver);
onfleetApi.workers.create(data);
```
Extended POST requests include `clone`, `forceComplete`, `batchCreate`, `autoAssign` on the tasks endpoint, `setSchedule` on the workers endpoint, `matchMetadata` on all supported entity endpoints, and `autoDispatch` on the teams endpoint:
Extended POST requests include `clone`, `forceComplete`, `batchCreate`, `autoAssign` on the *Tasks* endpoint; `setSchedule` on the *Workers* endpoint; `autoDispatch` on the *Teams* endpoint; and `matchMetadata` on all supported entities. For instance:
```js
onfleet.tasks.clone('<24_digit_id>');
onfleet.tasks.forceComplete('<24_digit_id>', '<completion_details>');
onfleet.tasks.batchCreate('<task_object_array>');
onfleet.tasks.autoAssign('<auto_assign_object>');
onfleet.<entities>.matchMetdata('<an_array_of_metadata_objects>');
onfleetApi.tasks.clone('<24_digit_ID>');
onfleetApi.tasks.forceComplete('<24_digit_ID>', { data });
onfleetApi.tasks.batchCreate({ data });
onfleetApi.tasks.autoAssign({ data });
onfleet.workers.setSchedule('<24_digit_id>', newSchedule);
onfleetApi.workers.setSchedule('<24_digit_ID>', { data });
onfleet.teams.autoDispatch('<24_digit_id>', dispatchConfig);
onfleetApi.teams.autoDispatch('<24_digit_ID>', { data });
onfleetApi.<entity_name_pluralized>.matchMetdata({ data });
```
For more details, check our documentation on [clone](https://docs.onfleet.com/reference#clone-task), [forceComplete](https://docs.onfleet.com/reference#complete-task), [batchCreate](https://docs.onfleet.com/reference#create-tasks-in-batch), [autoAssign](https://docs.onfleet.com/reference#automatically-assign-list-of-tasks), [setSchedule](https://docs.onfleet.com/reference#set-workers-schedule), [matchMetadata](https://docs.onfleet.com/reference#querying-by-metadata), and [autoDispatch](https://docs.onfleet.com/reference#team-auto-dispatch)
For more details, check our documentation on [`clone`](https://docs.onfleet.com/reference#clone-task), [`forceComplete`](https://docs.onfleet.com/reference#complete-task), [`batchCreate`](https://docs.onfleet.com/reference#create-tasks-in-batch), [`autoAssign`](https://docs.onfleet.com/reference#automatically-assign-list-of-tasks), [`setSchedule`](https://docs.onfleet.com/reference#set-workers-schedule), [`matchMetadata`](https://docs.onfleet.com/reference#querying-by-metadata), and [`autoDispatch`](https://docs.onfleet.com/reference#team-auto-dispatch).
#### PUT Requests
To update a document within an endpoint:
```js
update(<id>, <object>);
update("<24_digit_ID>", { data });
```
##### Examples of update()
##### Examples of `update()`
```js
const updateBody = {
name: "New Driver Name",
const newData = {
name: "Jack Driver",
};
onfleet.workers.update("<24_digit_id>", updateBody);
onfleetApi.workers.update("<24_digit_ID>", newData);
```
##### Examples of insertTask()
##### Examples of `insertTask()`
```js
onfleet.workers
.insertTask("kAQ*G5hnqlOq4jVvwtGNuacl", insertedTask)
.then((result) => {
// do something
});
onfleetApi.workers.insertTask("<24_digit_ID>", { data }).then((result) => { /* ... */ });
```
#### DELETE Requests
To delete a document within an endpoint:
```js
deleteOne(<id>);
deleteOne("<24_digit_ID>");
```
##### Examples of deleteOne()
##### Examples of `deleteOne()`
```js
onfleet.workers.deleteOne("<24_digit_id>");
onfleetApi.workers.deleteOne("<24_digit_ID>");
```

@@ -320,53 +258,58 @@

Get all the recipients (if it exist):
- Get all the recipients:
```js
onfleetApi.tasks
.get({ from: "1557936000000", to: "1558022400000" })
.then((tasks) => {
for (let task of tasks) {
if (task.recipients[0] !== undefined) {
// Do something with the recipients
}
}
})
.catch((err) => { /* ... */ });
```
```js
onfleet.tasks
.get({ from: "1557936000000", to: "1558022400000" })
.then((res) => {
for (let element of res) {
if (element.recipients[0] !== undefined) {
// do something with the recipients
}
- `async`/`await` can also be used like this:
```js
async function findAllWorkers() {
try {
let response = await onfleetApi.workers.get();
// Do something with the response
}
})
.catch((err) => {
// do something with the error
});
```
Async/await can also be used in this following case:
```js
async function findAllWorkers() {
try {
let response = await onfleet.workers.get();
// do something with the response
} catch (err) {
throw new Error(err);
catch (err) { /* ... */ }
}
}
findAllWorkers();
```
findAllWorkers();
```
### Things NOT to do
Inefficient pattern, use metadata instead:
- Inefficient pattern, use metadata instead:
```js
// DONT
onfleetApi.workers
.get()
.then((workers) => {
for (let worker of workers) {
for (let metadataEntry of worker.metadata) {
if (metadataEntry.name === "hasFreezer" && metadataEntry.value) {
// Do something
}
}
}
})
.catch((err) => { /* ... */ });
```js
onfleet.workers
.get()
.then((res) => {
for (let element of res) {
if (element.name == "some_name") {
onfleet.teams.get(element.teams[0]).then((result) => {
// do something with the team
});
// DO
onfleetApi.workers
.matchMetadata([{"name": "hasFreezer", "type": "boolean", "value": true}])
.then((workers) => {
for (let worker of workers) {
// Do something
}
}
})
.catch((err) => {
// do something with the error
});
```
})
.catch((err) => { /* ... */ });
```
*Go to [top](#onfleet-nodejs-wrapper)*.
# Onfleet Node.js Wrapper
![Travis (.org)](https://img.shields.io/travis/onfleet/node-onfleet.svg?style=popout-square)
[![GitHub](https://img.shields.io/github/license/onfleet/node-onfleet.svg?style=popout-square)](https://github.com/onfleet/node-onfleet/blob/master/LICENSE)
![David](https://img.shields.io/david/onfleet/node-onfleet.svg?style=popout-square)
[![npm (scoped)](https://img.shields.io/npm/v/@onfleet/node-onfleet.svg?style=popout-square)](https://www.npmjs.com/package/@onfleet/node-onfleet)
![GitHub top language](https://img.shields.io/github/languages/top/onfleet/node-onfleet.svg?style=popout-square)
[![npm](https://img.shields.io/npm/dt/@onfleet/node-onfleet.svg?style=popout-square)](https://www.npmjs.com/package/@onfleet/node-onfleet)
![Build](https://img.shields.io/travis/onfleet/node-onfleet.svg?style=popout-square)
[![License](https://img.shields.io/github/license/onfleet/node-onfleet.svg?style=popout-square)](https://github.com/onfleet/node-onfleet/blob/master/LICENSE)
[![Latest version](https://img.shields.io/npm/v/@onfleet/node-onfleet.svg?style=popout-square)](https://www.npmjs.com/package/@onfleet/node-onfleet)
![Top language](https://img.shields.io/github/languages/top/onfleet/node-onfleet.svg?style=popout-square)
![Dependencies](https://img.shields.io/david/onfleet/node-onfleet.svg?style=popout-square)
[![Downloads](https://img.shields.io/npm/dt/@onfleet/node-onfleet.svg?style=popout-square)](https://www.npmjs.com/package/@onfleet/node-onfleet)
*其他語言版本: [English](https://github.com/onfleet/node-onfleet/blob/master/README.md), [French](https://github.com/onfleet/node-onfleet/blob/master/README.fr.md), [正體中文](https://github.com/onfleet/node-onfleet/blob/master/README.zh-tw.md)*
> *其他語言版本*:
> [English](https://github.com/onfleet/node-onfleet/blob/master/README.md)
> [Français](https://github.com/onfleet/node-onfleet/blob/master/README.fr.md)
> [Español](https://github.com/onfleet/node-onfleet/blob/master/README.es.md)
欲了解本開源專案的背景,請參閱[我們的部落格](https://onfleet.com/blog/api-wrappers-explained/),如果您對於Onfleet應用程式介面或是我們產品有任何的問題,[歡迎在此留言](https://github.com/onfleet/node-onfleet/issues) 或直接聯繫 support@onfleet.com。
欲了解本開源專案的背景,請參閱[我們的部落格](https://onfleet.com/blog/api-wrappers-explained/),如果對於Onfleet應用程式介面或是我們產品有任何的問題,歡迎[在此留言](https://github.com/onfleet/pyonfleet/issues)或直接聯繫 support@onfleet.com。
### 目錄
- [Onfleet Node.js Wrapper](#onfleet-nodejs-wrapper)
+ [目錄](#目錄)
* [概要](#概要)
* [安裝](#安裝)
* [使用守則](#使用守則)
+ [金鑰認證](#金鑰認證)
+ [單元測試](#單元測試)
+ [API速限](#api速限)
+ [請求回應](#請求回應)
+ [支援的CRUD操作](#支援的CRUD操作)
- [GET 請求](#GET-請求)
* [使用get展示所有資源的範例](#使用get展示所有資源的範例)
* [使用get展示指定資源的範例](#使用get展示指定資源的範例)
* [展示指定地理位置的worker資源範例](#展示指定地理位置的worker資源範例)
- [POST 請求](#POST-請求)
* [使用create提交指定資源的範例](#使用create提交指定資源的範例)
- [PUT 請求](#PUT-請求)
* [使用update取代指定資源的範例](#使用update取代指定資源的範例)
* [使用insertTask取代指定資源的範例](#使用insertTask取代指定資源的範例)
- [DELETE 請求](#DELETE-請求)
* [使用deleteOne刪除指定資源的範例](#使用deleteOne刪除指定資源的範例)
+ [利用CRUD操作的範例](#利用CRUD操作的範例)
+ [錯誤的示範](#錯誤的示範)
+ [目錄](#目錄)
* [概要](#概要)
* [安裝](#安裝)
* [使用守則](#使用守則)
- [金鑰認證](#金鑰認證)
- [單元測試](#單元測試)
- [API速限](#api速限)
- [請求回應](#請求回應)
- [支援的CRUD操作](#支援的CRUD操作)
* [GET 請求](#GET-請求)
- [使用`get`展示所有資源的範例](#使用get展示所有資源的範例)
- [使用`get`展示指定資源的範例](#使用get展示指定資源的範例)
- [展示指定地理位置的`getByLocation`資源範例](#展示指定地理位置的getbylocation資源範例)
* [POST 請求](#POST-請求)
- [使用`create`提交指定資源的範例](#使用create提交指定資源的範例)
* [PUT 請求](#PUT-請求)
- [使用`update`取代指定資源的範例](#使用update取代指定資源的範例)
- [使用`insertTask`取代指定資源的範例](#使用inserttask取代指定資源的範例)
* [DELETE 請求](#DELETE-請求)
- [使用`deleteOne`刪除指定資源的範例](#使用deleteone刪除指定資源的範例)
- [利用CRUD操作的範例](#利用CRUD操作的範例)
- [錯誤的示範](#錯誤的示範)
## 概要
`node-onfleet` 提供一個快速又便捷的方式,以獲取Onfleet應用程式介面內的資料。
## 安裝
```
npm install @onfleet/node-onfleet
```
若是使用`TypeScript`,則需另外安裝[typed definition](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/onfleet__node-onfleet):
```
npm install @types/onfleet__node-onfleet
```
> 感謝 @marcobeltempo 的開源贊助
(感謝 @marcobeltempo 的開源贊助)
我們選用了`node-fetch`當作我們HTTP請求的工具,它使用了原生的Fetch API,支援promise,跟其他工具組相比依賴性上也較低。

@@ -65,3 +62,3 @@

```js
const onfleet = new Onfleet('<api_key>');
const onfleetApi = new Onfleet("<your_api_key>");
```

@@ -71,3 +68,3 @@

```js
const onfleet = new Onfleet('<api_key>', 30000) // 在此設定執行逾時參數為30000ms
const onfleetApi = new Onfleet("<your_api_key>", 30000);
```

@@ -77,7 +74,7 @@

```js
const onfleet = new Onfleet('<api_key>', 30000, {
LIMITER_RESERVOIR: 10, // default 20
LIMITER_WAIT_UPON_DEPLETION: 20000, // default 10000
LIMITER_MAX_CONCURRENT: 5, // default 1
LIMITER_MIN_TIME: 50, // default 50
const onfleetApi = new Onfleet("<your_api_key>", 30000, {
LIMITER_RESERVOIR: 10, // Default: 20
LIMITER_WAIT_UPON_DEPLETION: 20000, // Default: 10000
LIMITER_MAX_CONCURRENT: 5, // Default: 1
LIMITER_MIN_TIME: 50, // Default: 50
});

@@ -89,3 +86,3 @@ ```

```js
onfleet.verifyKey();
onfleetApi.verifyKey(); // Returns a boolean
```

@@ -96,3 +93,3 @@

### 單元測試
執行 `npm test`
`npm test`

@@ -106,6 +103,6 @@ ### API速限

### 支援的CRUD操作
Onfleet應用程式介面的基本URL為 `https://onfleet.com/api/v2`,下面為各endpoint所支援的函式列表:
下面為各endpoint所支援的函式列表:
| `<endpoint>` | GET | POST | PUT | DELETE |
|:------------:|:---------------------------------------------------:|:----------------------------------------------------------------------:|:------------------------------------:|:-------------:|
| Entity | GET | POST | PUT | DELETE |
| :-: | :-: | :-: | :-: | :-: |
| [Admins/Administrators](https://docs.onfleet.com/reference#administrators) | get() | create(obj), matchMetadata(obj) | update(id, obj) | deleteOne(id) |

@@ -126,21 +123,18 @@ | [Containers](https://docs.onfleet.com/reference#containers) | get(id, 'workers'), get(id, 'teams'), get(id, 'organizations') | x | update(id, obj) | x |

get();
get(<queryParam>);
```
##### 使用get展示所有資源的範例
##### 使用`get`展示所有資源的範例
```js
onfleet.workers.get().then((resultArray) => {
// 回應為一陣列
});
onfleetApi.workers.get().then((results) => { /* ... */ });
onfleetApi.workers.get({ queryParams }).then((results) => { /* ... */ });
```
部分的endpoint有支援*queryParam(查詢參數)*,詳情請參考[Onfleet官方文件](http://docs.onfleet.com):
```js
onfleet.workers.get({phones: '<電話號碼>'}).then((res) => {
// 回應為一worker物件
});
onfleet.tasks.get({from: '<from_time>', to: '<to_time>'}).then((result) => {
// 回應為ㄧ包含task物件的陣列
});
onfleetApi.workers.get({ phones: "<phone_number>" }).then((results) => { /* ... */ });
onfleetApi.tasks.get({ from: "<from_time>", to: "<to_time>" }).then((results) => { /* ... */ });
```
> **備註:** 查詢參數唯一的要求就是為一個JSON物件,舉例來說,`{ 'analytics': 'true' }`以及`{ analytics: true }`都會被接受。
> 查詢參數唯一的要求就是為一個JSON物件,舉例來說,`{ 'analytics': 'true' }`以及`{ analytics: true }`都會被接受

@@ -150,68 +144,45 @@

```js
get(<parameter>, <paramName>(非必要), <queryParam>(非必要));
get(<parameter>, <paramName> (optional), <queryParam> (optional));
```
*paramName*可以是: id, name, phone, shortId。
##### 使用get展示指定資源的範例
*paramName*可以是:
- `id`
- `name`
- `phone`
- `shortId`
##### 使用`get`展示指定資源的範例
```js
/**
* Workers節點的GET請求
*/
onfleet.workers.get('<24_digit_id>').then((result) => {
// 回應為一worker物件
});
onfleet.workers.get('<24_digit_id>', { analytics: true }).then((result) => {
// 回應為一worker物件
});
onfleetApi.workers.get("<24_digit_ID>").then((result) => { /* ... */ });
onfleetApi.workers.get("<24_digit_ID>", { analytics: true }).then((result) => { /* ... */ });
/**
* Tasks節點的GET請求
*/
onfleet.tasks.get('<shortId>', 'shortId').then((result) => {
// 回應為一task物件
});
onfleetApi.tasks.get("<shortId>", "shortId").then((result) => { /* ... */ });
/**
* Recipients節點的GET請求
*/
onfleet.recipients.get('<phone_number>', 'phone').then((result) => {
// 回應為一recipient物件
});
onfleet.recipients.get('<recipient_name>', 'name').then((result) => {
// 回應為一recipient物件
});
onfleet.recipients.get('<recipient_name>', 'name', {skipPhoneNumberValidation:true}).then((result) => {
// 回應為一recipient物件
});
onfleetApi.recipients.get("<phone_number>", "phone").then((result) => { /* ... */ });
onfleetApi.recipients.get("<recipient_name>", "name").then((result) => { /* ... */ });
onfleetApi.recipients
.get("<recipient_name>", "name", { skipPhoneNumberValidation: true })
.then((result) => { /* ... */ });
/**
* Containers節點的GET請求
*/
onfleet.containers.get('<24_digit_id>', 'workers').then((result) => {
// 回應為一container物件
});
onfleet.containers.get('<24_digit_id>', 'teams').then((result) => {
// 回應為一container物件
});
onfleet.containers.get('<24_digit_id>', 'organizations').then((result) => {
// 回應為一container物件
});
onfleetApi.containers.get("<24_digit_ID>", "workers").then((result) => { /* ... */ });
onfleetApi.containers.get("<24_digit_ID>", "teams").then((result) => {{ /* ... */ });
onfleetApi.containers.get("<24_digit_ID>", "organizations").then((result) => { /* ... */ });
```
欲使用地理位置來搜尋線上的worker,請使用`getByLocation`:
```js
getByLocation(<queryParam>);
getByLocation({ queryParams });
```
##### 展示指定地理位置的worker資源範例
##### 展示指定地理位置的`getByLocation`資源範例
```js
const location = {
const locationParams = {
longitude: -122.404,
latitude: 37.789,
radius: 10000
}
radius: 10000,
};
onfleet.workers.getByLocation(location).then((result) => {
// 顯示在線上,又符合地理位置的worker物件
});
onfleetApi.workers.getByLocation(locationParams).then((results) => { /* ... */ });
```
#### POST 請求

@@ -222,32 +193,36 @@ 提交某單一指定資源的指令如下:

```
##### 使用create提交指定資源的範例
##### 使用`create`提交指定資源的範例
```js
const driver = {
name: 'A Swartz',
phone: '617-342-8853',
teams: ['W*8bF5jY11Rk05E0bXBHiGg2'],
const data = {
name: "John Driver",
phone: "+16173428853",
teams: ["<team_ID>", "<team_ID> (optional)", ...],
vehicle: {
type: 'CAR',
description: 'Tesla Model 3',
licensePlate: 'FKNS9A',
color: 'purple',
type: "CAR",
description: "Tesla Model 3",
licensePlate: "FKNS9A",
color: "purple",
},
};
onfleet.workers.create(driver);
onfleetApi.workers.create(data);
```
其他延伸的POST請求包含了tasks節點上的`clone`, `forceComplete`, `batchCreate`, `autoAssign`,workers節點上的`setSchedule`, 所有支持的節點上的`matchMetadata`, 以及teams節點上的`autoDispatch`:
其他延伸的POST請求包含了*Tasks*節點上的`clone`, `forceComplete`, `batchCreate`, `autoAssign`,*Workers*節點上的`setSchedule`,*Teams*節點上的`autoDispatch`,以及所有支持節點上的`matchMetadata`:
```js
onfleet.tasks.clone('<24_digit_id>');
onfleet.tasks.forceComplete('<24_digit_id>', '<completion_details>');
onfleet.tasks.batchCreate('<task_object_array>');
onfleet.tasks.autoAssign('<auto_assign_object>');
onfleetApi.tasks.clone('<24_digit_ID>');
onfleetApi.tasks.forceComplete('<24_digit_ID>', { data });
onfleetApi.tasks.batchCreate({ data });
onfleetApi.tasks.autoAssign({ data });
onfleet.<entity>.matchMetadata('<array_of_metadata_object>');
onfleet.workers.setSchedule('<24_digit_id>', newSchedule);
onfleetApi.workers.setSchedule('<24_digit_ID>', { data });
onfleet.teams.autoDispatch('<24_digit_id>', dispatchConfig);
onfleetApi.teams.autoDispatch('<24_digit_ID>', { data });
onfleetApi.<entity_name_pluralized>.matchMetdata({ data });
```
參考資料:[clone](https://docs.onfleet.com/reference#clone-task), [forceComplete](https://docs.onfleet.com/reference#complete-task), [batchCreate](https://docs.onfleet.com/reference#create-tasks-in-batch), [autoAssign](https://docs.onfleet.com/reference#automatically-assign-list-of-tasks), [setSchedule](https://docs.onfleet.com/reference#set-workers-schedule), [matchMetadata](https://docs.onfleet.com/reference#querying-by-metadata), 以及[autoDispatch](https://docs.onfleet.com/reference#team-auto-dispatch)。
參考資料:[`clone`](https://docs.onfleet.com/reference#clone-task), [`forceComplete`](https://docs.onfleet.com/reference#complete-task), [`batchCreate`](https://docs.onfleet.com/reference#create-tasks-in-batch), [`autoAssign`](https://docs.onfleet.com/reference#automatically-assign-list-of-tasks), [`setSchedule`](https://docs.onfleet.com/reference#set-workers-schedule), [`matchMetadata`](https://docs.onfleet.com/reference#querying-by-metadata), 以及[`autoDispatch`](https://docs.onfleet.com/reference#team-auto-dispatch)。

@@ -257,16 +232,17 @@ #### PUT 請求

```js
update(<id>, <object>);
update("<24_digit_ID>", { data });
```
##### 使用update取代指定資源的範例
##### 使用`update`取代指定資源的範例
```js
const updateBody = {
name: 'New Driver Name',
const newData = {
name: "Jack Driver",
};
onfleet.workers.update('<24_digit_id>', updateBody);
onfleetApi.workers.update("<24_digit_ID>", newData);
```
##### 使用insertTask取代指定資源的範例
##### 使用`insertTask`取代指定資源的範例
```js
onfleet.workers.insertTask('kAQ*G5hnqlOq4jVvwtGNuacl', insertedTask).then(result => {
// 回應為worker類別的container物件
});
onfleetApi.workers.insertTask("<24_digit_ID>", { data }).then((result) => { /* ... */ });
```

@@ -277,49 +253,68 @@

```js
deleteOne(<id>);
deleteOne("<24_digit_ID>");
```
##### 使用deleteOne刪除指定資源的範例
##### 使用`deleteOne`刪除指定資源的範例
```js
onfleet.workers.deleteOne('<24_digit_id>');
onfleet.workers.deleteOne('<24_digit_ID>');
```
### 利用CRUD操作的範例
展示所有存在的recipients:
```js
onfleet.tasks.get({from:'<timestamp>', to:'<timestamp>'}).then((res) => {
for (let element of res) {
if (element.recipients[0] !== undefined) {
// do something with the recipients
- 展示所有存在的recipients:
```js
onfleetApi.tasks
.get({ from: "1557936000000", to: "1558022400000" })
.then((tasks) => {
for (let task of tasks) {
if (task.recipients[0] !== undefined) {
// Do something with the recipients
}
}
})
.catch((err) => { /* ... */ });
```
- `async`/`await` 函數的使用方式:
```js
async function findAllWorkers() {
try {
let response = await onfleetApi.workers.get();
// Do something with the response
}
catch (err) { /* ... */ }
}
}).catch((err) => {
// 錯誤回應
});
```
Async/await 函數的使用方式:
```js
async function findAllWorkers() {
try {
let response = await onfleet.workers.get();
// 對回應的陣列做出應用
} catch(err) {
throw new Error(err);
}
};
findAllWorkers();
```
findAllWorkers();
```
### 錯誤的示範
效率不佳的請求模型(請求中的請求),建議使用metadata:
```js
onfleet.workers.get().then((res) => {
for (let element of res) {
if (element.name == 'some_name') {
onfleet.teams.get(element.teams[0]).then((result) => {
// do something with the team
})
}
}
}).catch((err) => {
// 錯誤回應
});
```
- 效率不佳的請求模型(請求中的請求),建議使用metadata:
```js
// DONT
onfleetApi.workers
.get()
.then((workers) => {
for (let worker of workers) {
for (let metadataEntry of worker.metadata) {
if (metadataEntry.name === "hasFreezer" && metadataEntry.value) {
// Do something
}
}
}
})
.catch((err) => { /* ... */ });
// DO
onfleetApi.workers
.matchMetadata([{"name": "hasFreezer", "type": "boolean", "value": true}])
.then((workers) => {
for (let worker of workers) {
// Do something
}
})
.catch((err) => { /* ... */ });
```
*返回[頂端](#onfleet-nodejs-wrapper)*。
SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc