-
Notifications
You must be signed in to change notification settings - Fork 57
Expand file tree
/
Copy patheasypost.js
More file actions
395 lines (358 loc) · 13.6 KB
/
easypost.js
File metadata and controls
395 lines (358 loc) · 13.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
import os from 'os';
import superagent from 'superagent';
import util from 'util';
import { v4 as uuid } from 'uuid';
import pkg from '../package.json';
import Constants from './constants';
import ErrorHandler from './errors/error_handler';
import MissingParameterError from './errors/general/missing_parameter_error';
import AddressService from './services/address_service';
import ApiKeyService from './services/api_key_service';
import BatchService from './services/batch_service';
import BetaRateService from './services/beta_rate_service';
import BetaReferralCustomerService from './services/beta_referral_customer_service';
import BillingService from './services/billing_service';
import CarrierAccountService from './services/carrier_account_service';
import CarrierMetadataService from './services/carrier_metadata_service';
import CarrierTypeService from './services/carrier_type_service';
import ClaimService from './services/claim_service';
import CustomerPortalService from './services/customer_portal_service';
import CustomsInfoService from './services/customs_info_service';
import CustomsItemService from './services/customs_item_service';
import EmbeddableService from './services/embeddable_service';
import EndShipperService from './services/end_shipper_service';
import EventService from './services/event_service';
import FedExRegistrationService from './services/fedex_registration_service';
import InsuranceService from './services/insurance_service';
import LumaService from './services/luma_service';
import OrderService from './services/order_service';
import ParcelService from './services/parcel_service';
import PickupService from './services/pickup_service';
import RateService from './services/rate_service';
import ReferralCustomerService from './services/referral_customer_service';
import RefundService from './services/refund_service';
import ReportService from './services/report_service';
import ScanFormService from './services/scan_form_service';
import ShipmentService from './services/shipment_service';
import SmartRateService from './services/smart_rate_service';
import TrackerService from './services/tracker_service';
import UserService from './services/user_service';
import WebhookService from './services/webhook_service';
import Utils from './utils/util';
/**
* The client used to access services of the EasyPost API.
* This client is configured to use the latest production version of the EasyPost API.
* @param {string} key The API key to use for API requests made by this client.
* @param {Object} [options] Additional options to use for the underlying HTTP client (e.g. superagent, middleware, proxy configuration).
*/
export default class EasyPostClient {
constructor(key, options = {}) {
const { useProxy, timeout, baseUrl, superagentMiddleware, requestMiddleware } = options;
if (!key && !useProxy) {
throw new MissingParameterError({
message: util.format(Constants.MISSING_REQUIRED_PARAMETER, 'API Key'),
});
}
this.key = key;
this.timeout = timeout || EasyPostClient.DEFAULT_TIMEOUT;
this.baseUrl = baseUrl || EasyPostClient.DEFAULT_BASE_URL;
this.agent = superagent;
this.requestMiddleware = requestMiddleware;
this.requestHooks = [];
this.responseHooks = [];
this.Utils = new Utils();
if (superagentMiddleware) {
this.agent = superagentMiddleware(this.agent);
}
this._attachServices(EasyPostClient.SERVICES);
}
/**
* Add a request hook function.
* @param {(config: object) => void} hook
*/
addRequestHook(hook) {
this.requestHooks = [...this.requestHooks, hook];
}
/**
* Remove a request hook function.
* @param {(config: object) => void} hook
*/
removeRequestHook(hook) {
this.requestHooks = this.requestHooks.filter((h) => h !== hook);
}
/**
* Clear all request hooks.
*/
clearRequestHooks() {
this.requestHooks = [];
}
/**
* Add a response hook function.
* @param {(config: object) => void} hook
*/
addResponseHook(hook) {
this.responseHooks = [...this.responseHooks, hook];
}
/**
* Remove a response hook function.
* @param {(config: object) => void} hook
*/
removeResponseHook(hook) {
this.responseHooks = this.responseHooks.filter((h) => h !== hook);
}
/**
* Clear all response hooks.
*/
clearResponseHooks() {
this.responseHooks = [];
}
/**
* Create a copy of an {@link EasyPostClient} with overridden options.
* @param {EasyPostClient} client The `EasyPostClient` instance to clone.
* @param {Object} [options] The options to override.
* @returns {EasyPostClient} A new `EasyPostClient` instance.
*/
static copyClient(client, options = {}) {
const { apiKey, useProxy, timeout, baseUrl, superagentMiddleware, requestMiddleware } = options;
const agent = superagentMiddleware ? superagentMiddleware(client.agent) : client.agent;
return new EasyPostClient(apiKey || client.key, {
useProxy: useProxy || client.useProxy,
timeout: timeout || client.timeout,
baseUrl: baseUrl || client.baseUrl,
agent,
requestMiddleware: requestMiddleware || client.requestMiddleware,
});
}
/**
* Build request headers to be sent with each EasyPost API request, combined (or overridden) by any additional headers
* @param {Object} [additionalHeaders] Additional headers to combine or override with the default headers.
* @returns {Object} The headers to use for the request.
*/
static _buildHeaders(additionalHeaders = {}) {
return {
...EasyPostClient.DEFAULT_HEADERS,
...additionalHeaders,
};
}
/**
* Attach services to an {@link EasyPostClient} instance.
* @param {Map} services - A map of {@link BaseService}-based service classes to construct and attach to the client.
*/
_attachServices(services) {
Object.keys(services).forEach((s) => {
this[s] = services[s](this);
});
}
/**
* If the path passed in is a full URI, use it; otherwise, prepend the base url from the api.
* @param {string} path - The path to build.
* @returns {string} The full path to use for the HTTP request.
*/
_buildPath(path = '') {
if (path.indexOf('http') === 0) {
return path;
}
let completePath = this.baseUrl + path;
completePath = path.includes('beta') ? completePath.replace('/v2', '') : completePath;
return completePath;
}
/**
* Create a value to be passed to the responseHooks, based on the requestHooks
* value and the response.
* @param {Object} baseHooksValue - the value being passed the requestHooks
* @param {Object} response - the response from the superagent request
* @returns {Object} - the value to be passed to the responseHooks
*/
_createResponseHooksValue(baseHooksValue, response) {
return {
...baseHooksValue,
httpStatus: response.status,
responseBody: response.body,
headers: response.headers,
responseTimestamp: Date.now(),
};
}
/**
* Make an HTTP request.
* @param {string} [path] - The partial path to append to the base url for the request.
* @param {string} [method] - The HTTP method to use for the request, defaults to GET.
* @param {Object} [params] - The parameters to send with the request.
* @param {Object} [headers] - Additional headers to send with the request.
* @returns {*} The response from the HTTP request.
* @throws {ApiError} If the request fails.
*/
async _request(path = '', method = EasyPostClient.METHODS.GET, params = {}, headers = {}) {
const urlPath = this._buildPath(path);
const requestHeaders = EasyPostClient._buildHeaders(headers);
let request = this.agent[method](urlPath).set(requestHeaders);
if (this.requestMiddleware) {
request = this.requestMiddleware(request);
}
if (this.key) {
request.auth(this.key);
}
// it would be ideal if this "full url with params" could be gotten from superagent directly,
// but it doesn't seem to be possible
const url = new URL(urlPath);
if (params !== undefined) {
if (method === EasyPostClient.METHODS.GET || method === EasyPostClient.METHODS.DELETE) {
request.query(params);
Object.entries(params).forEach(([key, value]) => {
url.searchParams.append(key, value);
});
} else {
request.send(params);
}
}
const baseHooksValue = {
method,
path: url.toString(),
requestBody: request._data,
headers: requestHeaders,
requestTimestamp: Date.now(),
requestUUID: uuid(),
};
this.requestHooks.forEach((fn) => fn(baseHooksValue));
try {
const response = await request;
if (this.responseHooks.length > 0) {
const responseHooksValue = this._createResponseHooksValue(baseHooksValue, response);
this.responseHooks.forEach((fn) => fn(responseHooksValue));
}
return response;
} catch (error) {
if (error.response && error.response.body) {
const responseHooksValue = this._createResponseHooksValue(baseHooksValue, error.response);
this.responseHooks.forEach((fn) => fn(responseHooksValue));
throw ErrorHandler.handleApiError(error.response);
} else {
throw error;
}
}
}
/**
* Make a GET HTTP request.
* @param {string} path - The partial path to append to the base url for the request.
* @param {Object} [params] - The parameters to send with the request.
* @param {Object} [headers] - Additional headers to send with the request.
* @returns {*} The response from the HTTP request.
*/
_get(path, params = {}, headers = {}) {
return this._request(path, EasyPostClient.METHODS.GET, params, headers);
}
/**
* Make a POST HTTP request.
* @param {string} path - The partial path to append to the base url for the request.
* @param {Object} [params] - The parameters to send with the request.
* @param {Object} [headers] - Additional headers to send with the request.
* @returns {*} The response from the HTTP request.
*/
_post(path, params = {}, headers = {}) {
return this._request(path, EasyPostClient.METHODS.POST, params, headers);
}
/**
* Make a PUT HTTP request.
* @param {string} path - The partial path to append to the base url for the request.
* @param {Object} [params] - The parameters to send with the request.
* @param {Object} [headers] - Additional headers to send with the request.
* @returns {*} The response from the HTTP request.
*/
_put(path, params = {}, headers = {}) {
return this._request(path, EasyPostClient.METHODS.PUT, params, headers);
}
/**
* Make a PATCH HTTP request.
* @param {string} path - The partial path to append to the base url for the request.
* @param {Object} [params] - The parameters to send with the request.
* @param {Object} [headers] - Additional headers to send with the request.
* @returns {*} The response from the HTTP request.
*/
_patch(path, params = {}, headers = {}) {
return this._request(path, EasyPostClient.METHODS.PATCH, params, headers);
}
/**
* Make a DELETE HTTP request.
* @param {string} path - The partial path to append to the base url for the request.
* @param {Object} [params] - The parameters to send with the request.
* @param {Object} [headers] - Additional headers to send with the request.
* @returns {*} The response from the HTTP request.
*/
_delete(path, params = {}, headers = {}) {
return this._request(path, EasyPostClient.METHODS.DELETE, params, headers);
}
}
/**
* How many milliseconds in a second.
* @type {number}
*/
EasyPostClient.MS_SECOND = 1000;
/**
* The default timeout for all EasyPost API requests.
* @type {number}
*/
EasyPostClient.DEFAULT_TIMEOUT = 60 * EasyPostClient.MS_SECOND;
/**
* The default base URL for all production EasyPost API requests.
* @type {string}
*/
EasyPostClient.DEFAULT_BASE_URL = 'https://api.easypost.com/v2/';
/**
* The default headers used for all EasyPost API requests.
* @type {{'Accept': string, 'Content-Type': string, 'User-Agent': string}}
*/
EasyPostClient.DEFAULT_HEADERS = {
Accept: 'application/json',
'Content-Type': 'application/json',
'User-Agent': `EasyPost/v2 NodejsClient/${pkg.version} Nodejs/${
process.versions.node
} OS/${os.platform()} OSVersion/${os.release()} OSArch/${os.arch()}`,
};
/**
* A map of HTTP methods to their corresponding string values (for use with superagent).
* @type {{DELETE: string, POST: string, GET: string, PUT: string, PATCH: string}}
*/
EasyPostClient.METHODS = {
GET: 'get',
POST: 'post',
PUT: 'put',
PATCH: 'patch',
DELETE: 'del',
};
/**
* The services available for the client (end-user-facing name corresponding to a `BaseService`-based class).
* @type {Map}
*/
EasyPostClient.SERVICES = {
Address: AddressService,
ApiKey: ApiKeyService,
Batch: BatchService,
BetaRate: BetaRateService,
BetaReferralCustomer: BetaReferralCustomerService,
Billing: BillingService,
CarrierAccount: CarrierAccountService,
CarrierMetadata: CarrierMetadataService,
CarrierType: CarrierTypeService,
Claim: ClaimService,
CustomerPortal: CustomerPortalService,
CustomsInfo: CustomsInfoService,
CustomsItem: CustomsItemService,
Embeddable: EmbeddableService,
EndShipper: EndShipperService,
Event: EventService,
FedExRegistration: FedExRegistrationService,
Insurance: InsuranceService,
Luma: LumaService,
Order: OrderService,
Parcel: ParcelService,
Pickup: PickupService,
Rate: RateService,
ReferralCustomer: ReferralCustomerService,
Refund: RefundService,
Report: ReportService,
ScanForm: ScanFormService,
Shipment: ShipmentService,
SmartRate: SmartRateService,
Tracker: TrackerService,
User: UserService,
Webhook: WebhookService,
};