Skip to content

Commit

Permalink
update files to use ECMAScript modules
Browse files Browse the repository at this point in the history
  • Loading branch information
lisandrobigi-onfleet committed Sep 3, 2024
1 parent f10fe2f commit 6f9740a
Show file tree
Hide file tree
Showing 5 changed files with 2,401 additions and 436 deletions.
17 changes: 5 additions & 12 deletions lib/Resource.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,25 +14,18 @@ class Resource {
* @desc Defines the timeout value of the endpoint
* If none is specified, uses the default API timeout
*/
const preferredTimeout = timeout || this.api.api.timeout;
this.timeoutInMilliseconds = preferredTimeout;
this.timeoutInMilliseconds = timeout ?? this.api.api.timeout;
}

endpoints(params) {
/**
* @desc Initiates all the methods set in each resource configuration
* @param params is the configuration parsed in from each API endpoint
*/
for (const key in params) {
if (Object.prototype.hasOwnProperty.call(params, key)) {
this[key] = params[key];
this[key].timeoutInMilliseconds = this.timeoutInMilliseconds;
// Create functions for each method
this[key] = (...args) => {
return methods(params[key], this.api, ...args);
};
}
}
Object.entries(params).forEach(([key, value]) => {
this[key] = (...args) => methods(value, this.api, ...args);
this[key].timeoutInMilliseconds = this.timeoutInMilliseconds;
});
}
}

Expand Down
69 changes: 20 additions & 49 deletions lib/error.js
Original file line number Diff line number Diff line change
@@ -1,58 +1,29 @@
// Define custom error classes
// Define a function to create custom errors
const createError = (name, message, status = null, cause = null, request = null) => {
const error = new Error(message);
error.name = name;
error.status = status;
error.cause = cause;
error.request = request;
return error;
};

class ValidationError extends Error {
constructor(message) {
super(message);
this.name = 'ValidationError';
this.message = message;
}
}
// Create specific error types using the factory function
const ValidationError = (message) => createError('ValidationError', message);

class PermissionError extends Error {
constructor(message, status, cause, request) {
super(message);
this.name = 'PermissionError';
this.message = message;
this.status = status;
this.cause = cause;
this.request = request;
}
}
const PermissionError = (message, status, cause, request) =>
createError('PermissionError', message, status, cause, request);

class HttpError extends Error {
constructor(message, status, cause, request) {
super(message);
this.name = 'HttpError';
this.message = message;
this.status = status;
this.cause = cause;
this.request = request;
}
}
const HttpError = (message, status, cause, request) =>
createError('HttpError', message, status, cause, request);

class RateLimitError extends Error {
constructor(message, status, cause, request) {
super(message);
this.name = 'RateLimitError';
this.message = message;
this.status = status;
this.cause = cause;
this.request = request;
}
}
const RateLimitError = (message, status, cause, request) =>
createError('RateLimitError', message, status, cause, request);

class ServiceError extends Error {
constructor(message, status, cause, request) {
super(message);
this.name = 'ServiceError';
this.message = message;
this.status = status;
this.cause = cause;
this.request = request;
}
}
const ServiceError = (message, status, cause, request) =>
createError('ServiceError', message, status, cause, request);

// Export the custom error classes
// Export the custom error creators
export {
ValidationError,
PermissionError,
Expand Down
109 changes: 45 additions & 64 deletions lib/onfleet.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,11 @@ const DEFAULT_PATH = '/api';
const DEFAULT_API_VERSION = '/v2';
const DEFAULT_TIMEOUT = 70000;

// Import required modules
import * as constants from './constants.js';
import * as util from './util.js';
import { ValidationError } from './error.js';
import packageData from '../package.json' assert { type: 'json' };

// Import resources as ES modules
import Admins from './resources/Administrators.js';
import Containers from './resources/Containers.js';
import Destinations from './resources/Destinations.js';
Expand All @@ -25,7 +23,6 @@ import CustomFields from './resources/CustomFields.js';

const { name, version } = packageData;

// Create resources mapping as an object
const resources = {
Admins,
Administrators: Admins,
Expand All @@ -41,90 +38,74 @@ const resources = {
CustomFields,
};

/**
* @desc Onfleet object initiates all the resources
*/
class Onfleet {
get customHeaders() {
return this.headers;
}

set customHeaders(headers) {
this.headers = headers;
this.api.headers = { ...this.api.headers, ...this.customHeaders };
}
headers = {};

constructor(
apiKey,
userTimeout,
bottleneckOptions,
userTimeout = DEFAULT_TIMEOUT,
bottleneckOptions = null,
baseURL = DEFAULT_URL,
defaultPath = DEFAULT_PATH,
defaultApiVersion = DEFAULT_API_VERSION,
) {
if (!apiKey) {
throw new ValidationError('Onfleet API key not found, please obtain an API key from your organization admin');
}
if (userTimeout > 70000) {
throw new ValidationError('User-defined timeout has to be shorter than 70000ms');
} else {
this.apiKey = apiKey;
this.api = {
baseUrl: `${baseURL}${defaultPath}${defaultApiVersion}`,
timeout: userTimeout || DEFAULT_TIMEOUT,
headers: {
'Content-Type': 'application/json',
'User-Agent': `${name}-${version}`,
Authorization: `Basic ${util.encode(apiKey)}`,
},
};
if (bottleneckOptions) {
Onfleet.initBottleneckOptions(bottleneckOptions);
}

this.resources = resources;
this.initResources();
if (userTimeout > DEFAULT_TIMEOUT) {
throw new ValidationError(`User-defined timeout has to be shorter than ${DEFAULT_TIMEOUT}ms`);
}
}

static initBottleneckOptions(bottleneckOptions) {
const {
LIMITER_RESERVOIR,
LIMITER_WAIT_UPON_DEPLETION,
LIMITER_MAX_CONCURRENT,
LIMITER_MIN_TIME,
} = bottleneckOptions;

if (Number.isInteger(LIMITER_RESERVOIR) && LIMITER_RESERVOIR > 0 && LIMITER_RESERVOIR !== constants.LIMITER_RESERVOIR) {
constants.LIMITER_RESERVOIR = LIMITER_RESERVOIR;
}
this.apiKey = apiKey;
this.api = {
baseUrl: `${baseURL}${defaultPath}${defaultApiVersion}`,
timeout: userTimeout,
headers: {
'Content-Type': 'application/json',
'User-Agent': `${name}-${version}`,
Authorization: `Basic ${util.encode(apiKey)}`,
},
};

this.limiterSettings = this.initBottleneckOptions(bottleneckOptions || {});

this.resources = resources;
this.initResources();
}

if (Number.isInteger(LIMITER_WAIT_UPON_DEPLETION) && LIMITER_WAIT_UPON_DEPLETION > 0 && LIMITER_WAIT_UPON_DEPLETION !== constants.LIMITER_WAIT_UPON_DEPLETION) {
constants.LIMITER_WAIT_UPON_DEPLETION = LIMITER_WAIT_UPON_DEPLETION;
}
get customHeaders() {
return this.headers;
}

if (Number.isInteger(LIMITER_MAX_CONCURRENT) && LIMITER_MAX_CONCURRENT !== constants.LIMITER_MAX_CONCURRENT && LIMITER_MAX_CONCURRENT > 0) {
constants.LIMITER_MAX_CONCURRENT = LIMITER_MAX_CONCURRENT;
}
set customHeaders(headers) {
this.headers = headers;
this.api.headers = { ...this.api.headers, ...headers };
}

if (Number.isInteger(LIMITER_MIN_TIME) && LIMITER_MIN_TIME > 0 && LIMITER_MIN_TIME !== constants.LIMITER_MIN_TIME) {
constants.LIMITER_MIN_TIME = LIMITER_MIN_TIME;
}
initBottleneckOptions({
LIMITER_RESERVOIR = constants.LIMITER_RESERVOIR,
LIMITER_WAIT_UPON_DEPLETION = constants.LIMITER_WAIT_UPON_DEPLETION,
LIMITER_MAX_CONCURRENT = constants.LIMITER_MAX_CONCURRENT,
LIMITER_MIN_TIME = constants.LIMITER_MIN_TIME,
}) {
return {
reservoir: LIMITER_RESERVOIR,
waitUponDepletion: LIMITER_WAIT_UPON_DEPLETION,
maxConcurrent: LIMITER_MAX_CONCURRENT,
minTime: LIMITER_MIN_TIME,
};
}

initResources() {
// Initialize resources dynamically
for (let name in resources) {
Object.entries(resources).forEach(([name, Resource]) => {
const endpoint = name.toLowerCase();
this[endpoint] = new resources[name](this);
}
this[endpoint] = new Resource(this);
});
}

verifyKey() {
// Utility function to authenticate the API key
return util.authenticate(this.api);
async verifyKey() {
return await util.authenticate(this.api);
}
}

// Export the Onfleet class as the default export
export default Onfleet;
Loading

0 comments on commit 6f9740a

Please sign in to comment.