Consulta este documento en otro idioma:
English
Français
正體中文
Los invitamos a visitar nuestra publicación sobre el proyecto de librerías para la API para conocer más sobre nuestras iniciativas.
En caso de preguntas, pueden contactarnos a través de un issue aquí o escribirnos a support@onfleet.com.
- Onfleet Node.js Wrapper
La librería en Node.js de Onfleet nos permite un acceso fácil y cómodo a la API de Onfleet.
npm install @onfleet/node-onfleetPara TypeScript, debemos instalar la definición tipada:
npm install @types/onfleet__node-onfleet¡Agradecimientos especiales a @marcobeltempo por la contribución!
Antes de usar la librería, es indispensable obtener una llave para la API a través de alguno de los administradores de la organización a la que pertenecemos.
La creación e integración de llaves se realiza a través del panel principal de Onfleet.
Para utilizar la librería sólo tenemos que crear uns instancia de Onfleet usando la llave:
const onfleetApi = new Onfleet("<your_api_key>");Opcionalmente, se puede personalizar el timeout para hacerlo menor que el valor por defecto de la API de Onfleet (70,000 ms) suministrando un 2do parámetro:
const onfleetApi = new Onfleet("<your_api_key>", 30000);También de manera opcional, podemos personalizar las opciones de Bottleneck utilizando un 3er parámetro:
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
});Una vez tenemos la instancia de Onfleet podemos probar el endpoint de autenticación:
onfleetApi.verifyKey(); // Returns a booleannpm test
docker-compose up --build
La API impone un límite de 20 peticiones por segundo entre todas las peticiones de todas las llaves de la organización. Más detalles aquí.
La librería también implementa un limitador para prevenir excesos accidentales de los límites y, eventualmente, posibles sanciones.
Las respuestas de esta librería son instancias de Response.
Estas son las operaciones disponibles para cada endpoint:
| Entity | 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 | insertTask(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 | x | x |
| Recipients | get(id) get(name, 'name') get(phone, 'phone') |
create(obj) matchMetadata(obj) |
update(id, obj) | x |
| Route Plans | get(id) get(queryParams="") |
create(obj) | update(id, obj) addTasksToRoutePlan(id, obj) |
deleteOne(id) |
| Tasks | get(query) get(id) get(shortId, 'shortId') |
create(obj) clone(id) clone(id, obj) forceComplete(id, obj) batchCreate(obj) batchCreateAsync(obj) getBatch(id) autoAssign(obj) matchMetadata(obj) |
update(id, obj) | deleteOne(id) |
| Teams | get() get(id) getWorkerEta(id, obj) getTasks(id) |
create(obj) autoDispatch(id, obj) matchMetadata(obj) |
update(id, obj) | deleteOne(id) |
| Webhooks | get() | create(obj) | x | deleteOne(id) |
| Workers | get() get(query) get(id) getByLocation(obj) getSchedule(id) getTasks(id) |
create(obj) setSchedule(id, obj) matchMetadata(obj) getDeliveryManifest(obj) |
update(id, obj) insertTask(id, obj) |
deleteOne(id) |
| Custom Fields | get(integration) | create(obj) | update(obj) | delete(obj) |
Para obtener todos los elementos disponibles en un recurso, éstas llamadas retornan un Promise con el arreglo de los resultados:
get();onfleetApi.workers.get().then((results) => { /* ... */ });
onfleetApi.workers.get({ queryParams }).then((results) => { /* ... */ });Opcionalmente, podemos utilizar un objeto JSON con parámetros de búsqueda en los recursos que lo soportan.
En la documentación de la API se describe qué recursos lo permiten.
onfleetApi.workers.get({ phones: "<phone_number>" }).then((results) => { /* ... */ });
onfleetApi.tasks.get({ from: "<from_time>", to: "<to_time>" }).then((results) => { /* ... */ });Tanto
{ 'analytics': 'true' }como{ analytics: true }funcionan parámetros de búsqueda porque ambos representan un objeto JSON válido
Para obtener uno de los elementos de un endpoint, si el parámetreo opcional paramName no es suministrado, la libraría buscará por ID. Si paramName es suministrado, se utilizará paramName:
get(<parameter>, <paramName> (optional), <queryParam> (optional));Posibles valores de paramName:
idnamephoneshortId
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) => { /* ... */ });Para obtener un información de un batch específico
onfleetAPI.tasks.getBatch("<jobId>","jobId").then((result) => { /* ... */ });Para obtener un driver según su ubicación, podemos utilizar la función getByLocation:
getByLocation({ queryParams });const locationParams = {
longitude: -122.404,
latitude: 37.789,
radius: 10000,
};
onfleetApi.workers.getByLocation(locationParams).then((results) => { /* ... */ });Para crear un elemento de un recurso:
create({ data });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);const data = {
hubId: "<hubId>", // Required
workerId: "<workerId", // Required
googleApiKey: "<google_direction_api_key>", // Optional
startDate: "<startDate>", // Optional
endDate: "<endDate>" // Optional
};
onfleetApi.workers.getDeliveryManifest(data);Otras peticiones POST incluyen clone, forceComplete, batchCreate,batchCreateAsync, autoAssign en el recurso Tasks; setSchedule en el recurso Workers; autoDispatch en el recurso Teams; y matchMetadata en todos los recursos que lo soportan. Por ejemplo:
onfleetApi.tasks.clone('<24_digit_ID>');
onfleetApi.tasks.forceComplete('<24_digit_ID>', { data });
onfleetApi.tasks.batchCreate({ data });
onfleetApi.tasks.batchCreateAsync({ data });
onfleetApi.tasks.autoAssign({ data });
onfleetApi.workers.setSchedule('<24_digit_ID>', { data });
onfleetAPI.workers.getDeliveryManifest({ data })
onfleetApi.teams.autoDispatch('<24_digit_ID>', { data });
onfleetApi.<entity_name_pluralized>.matchMetadata({ data });Para más información, podemos consultar la documentación sobre clone, forceComplete, batchCreate, autoAssign, setSchedule, getDeliveryManifest, matchMetadata y autoDispatch.
Para modificar un elemento de un recurso:
update("<24_digit_ID>", { data });const newData = {
name: "Jack Driver",
};
onfleetApi.workers.update("<24_digit_ID>", newData);onfleetApi.workers.insertTask("<24_digit_ID>", { data }).then((result) => { /* ... */ });Para eliminar un elemento de un recurso:
deleteOne("<24_digit_ID>");onfleetApi.workers.deleteOne("<24_digit_ID>");-
Obetener todos los 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) => { /* ... */ });
-
Podemos usar
async/awaitasí:async function findAllWorkers() { try { let response = await onfleetApi.workers.get(); // Do something with the response } catch (err) { /* ... */ } } findAllWorkers();
- Patrón ineficiente, debemos usar metadata:
// 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) => { /* ... */ });
Ir al inicio.