Skip to content

Threeethan/node-onfleet

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

45 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Onfleet Node.js Wrapper

Travis (.org) GitHub David npm (scoped) GitHub top language npm

Read this document in another language: English, French, 正體中文

Visit our blog post on the API wrapper project to learn more about our initiatives. If you have any questions, please reach out to Onfleet 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 your organization admin. Creation and integration of API keys are performed through the Onfleet dashboard.

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

const onfleet = new Onfleet("<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:

const onfleet = new Onfleet("<api_key>", 30000); // This will set your wrappers to timeout at 30000ms instead of 70000ms

As an optional field, you can introduce an options object for Bottleneck.

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

Authentication

Once the Onfleet object is created, you can use a utility function to test on the authentication endpoint, this function returns a boolean:

onfleet.verifyKey();

Once the Onfleet object is created, you will get access to all the API endpoints as documented in the Onfleet API documentation. Here are some usage case:

Unit Testing

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. We have implemented a limiter on the wrapper itself to avoid you from unintentionally exceeding your rate limitations and eventually be banned for.

Responses

The node-onfleet API wrapper returns the body of a Response object.

Supported CRUD Operations

The base URL for the Onfleet API is https://onfleet.com/api/v2, here are the supported CRUD operations for each endpoint:

<endpoint> GET POST PUT DELETE
Admins/Administrators get() create(obj), matchMetadata(obj) update(id, obj) deleteOne(id)
Containers get(id, 'workers'), get(id, 'teams'), get(id, 'organizations') x update(id, obj) x
Destinations get(id) create(obj), matchMetadata(obj) x x
Hubs get() create(obj) update(id, obj) x
Organization get(), get(id) x insertTask(id, obj) x
Recipients get(id), get(name, 'name'), get(phone, 'phone') create(obj), matchMetadata(obj) update(id, obj) x
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 get(), get(id), getWorkerEta(id, obj) create(obj), autoDispatch(id, obj) update(id, obj), insertTask(id, obj) deleteOne(id)
Webhooks get() create(obj) x deleteOne(id)
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:

get();
get(<queryParam> (optional));
Examples of get()
onfleet.workers.get().then((resultArray) => {
  // do something with the array containing all workers
});

Option to use query parameters for some certain endpoints, refer back to API documents for endpoints that support query parameters:

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

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 }

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:

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

Options for paramName: id, name, phone, shortId (see table above).

Examples of get(param)
/**
 * 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
});

/**
 * GET for Tasks
 */
onfleet.tasks.get("<shortId>", "shortId").then((result) => {
  // do something with the one result found
});

/**
 * 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
  .get("<recipient_name>", "name", { skipPhoneNumberValidation: true })
  .then((result) => {
    // do something with the one result found
  });

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

To get a driver by location, use the getByLocation function:

getByLocation(<queryParam>);
Examples of getByLocation
const location = {
  longitude: -122.404,
  latitude: 37.789,
  radius: 10000,
};

onfleet.workers.getByLocation(location).then((result) => {
  // shows the on-duty workers at the specific location
});

POST Requests

To create a document within an endpoint:

create(<object>);
Examples of create()
const driver = {
  name: "A Swartz",
  phone: "617-342-8853",
  teams: ["W*8bF5jY11Rk05E0bXBHiGg2"],
  vehicle: {
    type: "CAR",
    description: "Tesla Model 3",
    licensePlate: "FKNS9A",
    color: "purple",
  },
};
onfleet.workers.create(driver);

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:

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

onfleet.workers.setSchedule('<24_digit_id>', newSchedule);

onfleet.teams.autoDispatch('<24_digit_id>', dispatchConfig);

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(<id>, <object>);
Examples of update()
const updateBody = {
  name: "New Driver Name",
};
onfleet.workers.update("<24_digit_id>", updateBody);
Examples of insertTask()
onfleet.workers
  .insertTask("kAQ*G5hnqlOq4jVvwtGNuacl", insertedTask)
  .then((result) => {
    // do something
  });

DELETE Requests

To delete a document within an endpoint:

deleteOne(<id>);
Examples of deleteOne()
onfleet.workers.deleteOne("<24_digit_id>");

Examples of utilizing your CRUD operations

Get all the recipients (if it exist):

onfleet.tasks
  .get({ from: "1557936000000", to: "1558022400000" })
  .then((res) => {
    for (let element of res) {
      if (element.recipients[0] !== undefined) {
        // do something with the recipients
      }
    }
  })
  .catch((err) => {
    // do something with the error
  });

Async/await can also be used in this following case:

async function findAllWorkers() {
  try {
    let response = await onfleet.workers.get();
    // do something with the response
  } catch (err) {
    throw new Error(err);
  }
}

findAllWorkers();

Things NOT to do

Inefficient pattern, use metadata instead:

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

About

Onfleet API Wrapper in NodeJS

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Languages

  • JavaScript 100.0%