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

Onfleet's Node.js API Wrapper Package

  • 1.3.1
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
4.7K
increased by3.29%
Maintainers
3
Weekly downloads
 
Created
Source

Onfleet Node.js Wrapper

Build License Latest version Top language Dependencies Downloads

Read this document in another language:
Français
正體中文
Español

Visit our blog post on the API wrapper project to learn more about our initiatives.
If you have any questions, please reach us by submitting an issue here or contact support@onfleet.com.

Table of contents

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:

npm install @types/onfleet__node-onfleet

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.

Creation and integration of API keys are performed through the Onfleet dashboard.

To start utilizing the library, you simply need to create an Onfleet object with your API key:

const onfleetApi = new Onfleet("<your_api_key>");

Optionally, you can introduce a customized timeout that is less than the default Onfleet API timeout (70,000 ms) by providing a 2nd parameter:

const onfleetApi = new Onfleet("<your_api_key>", 30000);

Optionally again, you can introduce an options object for Bottleneck as a 3rd parameter:

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
});

Authentication

Once the Onfleet object is created, you can test on the authentication endpoint:

onfleetApi.verifyKey();  // Returns a boolean

Unit Testing

npm test

Unit testing using Docker

docker-compose up --build

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.

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.

Supported CRUD Operations

Here are the operations available for each entity:

EntityGETPOSTPUTDELETE
Admins/Administratorsget()create(obj)
matchMetadata(obj)
update(id, obj)deleteOne(id)
Containersget(id, 'workers')
get(id, 'teams')
get(id, 'organizations')
xinsertTask(id, obj)x
Destinationsget(id)create(obj)
matchMetadata(obj)
xx
Hubsget()create(obj)update(id, obj)x
Organizationget()
get(id)
xxx
Recipientsget(id)
get(name, 'name')
get(phone, 'phone')
create(obj)
matchMetadata(obj)
update(id, obj)x
Tasksget(query)
get(id)
get(shortId, 'shortId')
create(obj)
clone(id)
clone(id, obj)
forceComplete(id, obj)
batchCreate(obj)
autoAssign(obj)
matchMetadata(obj)
update(id, obj)deleteOne(id)
Teamsget()
get(id)
getWorkerEta(id, obj)
getTasks(id)
create(obj)
autoDispatch(id, obj)
update(id, obj)deleteOne(id)
Webhooksget()create(obj)xdeleteOne(id)
Workersget()
get(query)
get(id)
getByLocation(obj)
getSchedule(id)
getTasks(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:

get();
Examples of get()
onfleetApi.workers.get().then((results) => { /* ... */ });
onfleetApi.workers.get({ queryParams }).then((results) => { /* ... */ });

Optionally you can send a JSON object of query params for some certain endpoints.
Refer back to API documentation for endpoints that support query parameters.

onfleetApi.workers.get({ phones: "<phone_number>" }).then((results) => { /* ... */ });

onfleetApi.tasks.get({ from: "<from_time>", to: "<to_time>" }).then((results) => { /* ... */ });

Both { 'analytics': 'true' } and { analytics: true } work as query params since they represent a valid JSON object

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:

get(<parameter>, <paramName> (optional), <queryParam> (optional));

paramName can be any of:

  • id
  • name
  • phone
  • shortId
Examples of get(param)
onfleetApi.workers.get("<24_digit_ID>").then((result) => { /* ... */ });
onfleetApi.workers.get("<24_digit_ID>", { analytics: true }).then((result) => { /* ... */ });

onfleetApi.tasks.get("<shortId>", "shortId").then((result) => { /* ... */ });

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) => { /* ... */ });

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:

getByLocation({ queryParams });
Examples of getByLocation
const locationParams = {
  longitude: -122.404,
  latitude: 37.789,
  radius: 10000,
};

onfleetApi.workers.getByLocation(locationParams).then((results) => { /* ... */ });
POST Requests

To create a document within an endpoint:

create({ data });
Examples of create()
const data = {
  name: "John Driver",
  phone: "+16173428853",
  teams: ["<team_ID>", "<team_ID> (optional)", ...],
  vehicle: {
    type: "CAR",
    description: "Tesla Model 3",
    licensePlate: "FKNS9A",
    color: "purple",
  },
};

onfleetApi.workers.create(data);

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:

onfleetApi.tasks.clone('<24_digit_ID>');
onfleetApi.tasks.forceComplete('<24_digit_ID>', { data });
onfleetApi.tasks.batchCreate({ data });
onfleetApi.tasks.autoAssign({ data });

onfleetApi.workers.setSchedule('<24_digit_ID>', { data });

onfleetApi.teams.autoDispatch('<24_digit_ID>', { data });

onfleetApi.<entity_name_pluralized>.matchMetadata({ data });

For more details, check our documentation on clone, forceComplete, batchCreate, autoAssign, setSchedule, matchMetadata, and autoDispatch.

PUT Requests

To update a document within an endpoint:

update("<24_digit_ID>", { data });
Examples of update()
const newData = {
  name: "Jack Driver",
};

onfleetApi.workers.update("<24_digit_ID>", newData);
Examples of insertTask()
onfleetApi.workers.insertTask("<24_digit_ID>", { data }).then((result) => { /* ... */ });
DELETE Requests

To delete a document within an endpoint:

deleteOne("<24_digit_ID>");
Examples of deleteOne()
onfleetApi.workers.deleteOne("<24_digit_ID>");

Examples of utilizing your CRUD operations

  • Get all the recipients:

    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 can also be used like this:

    async function findAllWorkers() {
      try {
        let response = await onfleetApi.workers.get();
        // Do something with the response
      }
      catch (err) { /* ... */ }
    }
    
    findAllWorkers();
    

Things NOT to do

  • Inefficient pattern, use metadata instead:
    // 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) => { /* ... */ });
    

Go to top.

Keywords

FAQs

Package last updated on 22 Jun 2022

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

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