Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .prettierrc.yml
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
trailingComma: all
singleQuote: true
printWidth: 100
printWidth: 120
6 changes: 2 additions & 4 deletions src/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,9 @@ export default class Constants {
static INVALID_WEBHOOK_SIGNATURE = 'Webhook does not contain a valid HMAC signature.';
static MISSING_REQUIRED_PARAMETER = 'Missing required parameter: %s.';
static NO_OBJECT_FOUND = 'No %s found.';
static NO_PAYMENT_METHODS =
'No payment methods are set up. Please add a payment method and try again.';
static NO_PAYMENT_METHODS = 'No payment methods are set up. Please add a payment method and try again.';
static API_DID_NOT_RETURN_ERROR_DETAILS = 'API did not return error details.';
static WEBHOOK_DOES_NOT_MATCH =
'Webhook received did not originate from EasyPost or had a webhook secret mismatch.';
static WEBHOOK_DOES_NOT_MATCH = 'Webhook received did not originate from EasyPost or had a webhook secret mismatch.';
static END_OF_PAGINATION = 'There are no more pages to retrieve.';
static ERROR_DESERIALIZATION = 'Error deserializing JSON response';
static Utils = new Utils();
Expand Down
24 changes: 7 additions & 17 deletions src/easypost.ts
Original file line number Diff line number Diff line change
Expand Up @@ -233,10 +233,8 @@ export default class EasyPostClient {
* @returns {EasyPostClient} A new `EasyPostClient` instance.
*/
static copyClient(client: EasyPostClient, options: ClientOptions = {}): EasyPostClient {
const { apiKey, useProxy, timeout, baseUrl, httpMiddleware, requestMiddleware, httpClient } =
options;
const nextHttpClient =
httpClient || (httpMiddleware ? httpMiddleware(client.httpClient) : client.httpClient);
const { apiKey, useProxy, timeout, baseUrl, httpMiddleware, requestMiddleware, httpClient } = options;
const nextHttpClient = httpClient || (httpMiddleware ? httpMiddleware(client.httpClient) : client.httpClient);

return new EasyPostClient(apiKey || client.key, {
useProxy: useProxy || client.useProxy,
Expand Down Expand Up @@ -338,9 +336,7 @@ export default class EasyPostClient {
nodeVersion = process.versions && process.versions.node ? process.versions.node : nodeVersion;
osName = process.platform || osName;
osArch = process.arch || osArch;
osVersion =
(process.env && (process.env.OS_VERSION || process.env.OSTYPE || process.env.OS)) ||
osVersion;
osVersion = (process.env && (process.env.OS_VERSION || process.env.OSTYPE || process.env.OS)) || osVersion;
}

return `EasyPost/v2 NodejsClient/${pkgVersion} Nodejs/${nodeVersion} OS/${osName} OSVersion/${osVersion} OSArch/${osArch}`;
Expand All @@ -366,8 +362,7 @@ export default class EasyPostClient {
return path;
}

const normalizedPath =
this.baseUrl.endsWith('/') && path.startsWith('/') ? path.slice(1) : path;
const normalizedPath = this.baseUrl.endsWith('/') && path.startsWith('/') ? path.slice(1) : path;
let completePath = this.baseUrl + normalizedPath;
completePath = path.includes('beta') ? completePath.replace('/v2', '') : completePath;

Expand Down Expand Up @@ -411,8 +406,7 @@ export default class EasyPostClient {
const requestHeaders = EasyPostClient._buildHeaders(headers);
const url = new URL(urlPath);
const isQueryMethod =
normalizedMethod === EasyPostClient.METHODS.GET ||
normalizedMethod === EasyPostClient.METHODS.DELETE;
normalizedMethod === EasyPostClient.METHODS.GET || normalizedMethod === EasyPostClient.METHODS.DELETE;
let requestBody: RequestBody | undefined;

if (params !== undefined) {
Expand Down Expand Up @@ -515,8 +509,7 @@ export default class EasyPostClient {
method: normalizedMethod.toUpperCase(),
headers: requestHeaders,
body:
normalizedMethod === EasyPostClient.METHODS.GET ||
normalizedMethod === EasyPostClient.METHODS.DELETE
normalizedMethod === EasyPostClient.METHODS.GET || normalizedMethod === EasyPostClient.METHODS.DELETE
? undefined
: JSON.stringify(middlewareRequest._data),
});
Expand Down Expand Up @@ -552,10 +545,7 @@ export default class EasyPostClient {
this.responseHooks.forEach((fn) => fn(responseHooksValue));
throw ErrorHandler.handleApiError(handledError);
} else if (handledError.response && handledError.response.body) {
const responseHooksValue = this._createResponseHooksValue(
baseHooksValue,
handledError.response,
);
const responseHooksValue = this._createResponseHooksValue(baseHooksValue, handledError.response);
this.responseHooks.forEach((fn) => fn(responseHooksValue));
throw ErrorHandler.handleApiError(handledError.response);
} else {
Expand Down
3 changes: 1 addition & 2 deletions src/models/customs_info.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,5 @@ export default class CustomsInfo extends EasyPostObject {
declare eel_pfc?: string | null;
declare non_delivery_option?: 'abandon' | 'return' | null;
declare restriction_comments?: string | null;
declare restriction_type?:
'none' | 'other' | 'quarantine' | 'sanitary_phytosanitary_inspection' | null;
declare restriction_type?: 'none' | 'other' | 'quarantine' | 'sanitary_phytosanitary_inspection' | null;
}
5 changes: 1 addition & 4 deletions src/models/order.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,7 @@ export default class Order extends EasyPostObject {
* @returns {Rate} - The lowest rate
* @throws {FilteringError} - If no applicable rates are found
*/
lowestRate(
carriers?: string[],
services?: string[],
): ReturnType<typeof Constants.Utils.getLowestRate> {
lowestRate(carriers?: string[], services?: string[]): ReturnType<typeof Constants.Utils.getLowestRate> {
const rates = this.rates || [];

return Constants.Utils.getLowestRate(rates, carriers, services);
Expand Down
10 changes: 4 additions & 6 deletions src/models/pickup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,12 +32,10 @@ export default class Pickup extends EasyPostObject {
* @returns {Rate} - The lowest rate
* @throws {FilteringError} - If no applicable rates are found
*/
lowestRate(
carriers?: string[],
services?: string[],
): ReturnType<typeof Constants.Utils.getLowestRate> {
const rates = ((this as Pickup & { pickup_rates?: unknown[] }).pickup_rates ||
[]) as Parameters<typeof Constants.Utils.getLowestRate>[0];
lowestRate(carriers?: string[], services?: string[]): ReturnType<typeof Constants.Utils.getLowestRate> {
const rates = ((this as Pickup & { pickup_rates?: unknown[] }).pickup_rates || []) as Parameters<
typeof Constants.Utils.getLowestRate
>[0];

return Constants.Utils.getLowestRate(rates, carriers, services);
}
Expand Down
5 changes: 1 addition & 4 deletions src/models/shipment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,10 +50,7 @@ export default class Shipment extends EasyPostObject {
* @returns {Rate} - The lowest rate
* @throws {FilteringError} - If no applicable rates are found
*/
lowestRate(
carriers?: string[],
services?: string[],
): ReturnType<typeof Constants.Utils.getLowestRate> {
lowestRate(carriers?: string[], services?: string[]): ReturnType<typeof Constants.Utils.getLowestRate> {
const rates = ((this as Shipment & { rates?: unknown[] }).rates || []) as Parameters<
typeof Constants.Utils.getLowestRate
>[0];
Expand Down
5 changes: 1 addition & 4 deletions src/services/address_service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -106,10 +106,7 @@ export default (easypostClient: EasyPostClient) =>
* @param {Number} pageSize The number of records to return on each page
* @returns {EasyPostObject|Promise<never>} The retrieved {@link EasyPostObject}-based class instance, or a `Promise` that rejects with an error.
*/
static async getNextPage(
addresses: PaginationCollection,
pageSize?: number,
): Promise<AddressCollection> {
static async getNextPage(addresses: PaginationCollection, pageSize?: number): Promise<AddressCollection> {
const url = 'addresses';
return this._getNextPage(url, 'addresses', addresses, pageSize);
}
Expand Down
13 changes: 3 additions & 10 deletions src/services/base_service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -150,9 +150,7 @@ export default (easypostClient: any) =>
}

Object.keys(response as Record<string, unknown>).forEach((key) => {
plainObject[key] = this._toPlainEasyPostObject(
(response as Record<string, unknown>)[key],
);
plainObject[key] = this._toPlainEasyPostObject((response as Record<string, unknown>)[key]);
});

return plainObject;
Expand Down Expand Up @@ -180,10 +178,7 @@ export default (easypostClient: any) =>

if (isObjectRecord(response)) {
let classObject: any;
if (
typeof response.object === 'string' &&
(RESOURCES as Record<string, any>)[response.object] !== undefined
) {
if (typeof response.object === 'string' && (RESOURCES as Record<string, any>)[response.object] !== undefined) {
classObject = new (RESOURCES as Record<string, any>)[response.object]();
} else if (
typeof response.id === 'string' &&
Expand All @@ -192,9 +187,7 @@ export default (easypostClient: any) =>
] !== undefined
) {
const className = response.id.substring(0, response.id.indexOf('_'));
classObject = new (EASYPOST_OBJECT_ID_PREFIX_TO_CLASS_NAME_MAP as Record<string, any>)[
className
]();
classObject = new (EASYPOST_OBJECT_ID_PREFIX_TO_CLASS_NAME_MAP as Record<string, any>)[className]();
} else {
classObject = new EasyPostObject();
}
Expand Down
5 changes: 1 addition & 4 deletions src/services/batch_service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,10 +85,7 @@ export default (easypostClient: EasyPostClient) =>
* @param {string} fileFormat - The format of the label to generate. Defaults to 'pdf'.
* @returns {Batch} - The updated batch.
*/
static async generateLabel(
id: string,
fileFormat: string = DEFAULT_LABEL_FORMAT,
): Promise<Batch> {
static async generateLabel(id: string, fileFormat: string = DEFAULT_LABEL_FORMAT): Promise<Batch> {
const url = `batches/${id}/label`;
const wrappedParams = { file_format: fileFormat };

Expand Down
4 changes: 1 addition & 3 deletions src/services/beta_rate_service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,7 @@ export default (easypostClient: EasyPostClient) =>
* @param {Object} params - Map of parameters for the API call
* @returns {Object} - Stateless rates response
*/
static async retrieveStatelessRates(
params: Record<string, unknown>,
): Promise<BetaRateRetrieveResponse> {
static async retrieveStatelessRates(params: Record<string, unknown>): Promise<BetaRateRetrieveResponse> {
const url = 'beta/rates';
const wrappedParams = {
shipment: params,
Expand Down
4 changes: 1 addition & 3 deletions src/services/beta_referral_customer_service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,9 +86,7 @@ export default (easypostClient: EasyPostClient) =>
* Creates a client secret to use with Stripe when adding a credit card.
* @returns {object} - A JSON object representing the client secret.
*/
static async createBankAccountClientSecret(
returnUrl: string | null,
): Promise<BetaClientSecretResponse> {
static async createBankAccountClientSecret(returnUrl: string | null): Promise<BetaClientSecretResponse> {
const url = 'beta/financial_connections_sessions';
if (returnUrl) {
const response = await easypostClient._post(url, { return_url: returnUrl });
Expand Down
5 changes: 1 addition & 4 deletions src/services/billing_service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,10 +78,7 @@ export default (easypostClient: EasyPostClient) =>
*/
static async _getPaymentInfo(priority: string): Promise<[string, string]> {
const paymentMethods = await this.retrievePaymentMethods();
const paymentMethodMap: Record<
string,
'primary_payment_method' | 'secondary_payment_method'
> = {
const paymentMethodMap: Record<string, 'primary_payment_method' | 'secondary_payment_method'> = {
primary: 'primary_payment_method',
secondary: 'secondary_payment_method',
};
Expand Down
5 changes: 1 addition & 4 deletions src/services/carrier_account_service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,10 +52,7 @@ export default (easypostClient: EasyPostClient) =>
* @param {Object} params - Parameters for the carrier account to be updated.
* @returns {CarrierAccount} - The updated carrier account.
*/
static async update(
id: string,
params: CarrierAccountCreateParameters,
): Promise<CarrierAccount> {
static async update(id: string, params: CarrierAccountCreateParameters): Promise<CarrierAccount> {
const wrappedParams = { carrier_account: params };

try {
Expand Down
5 changes: 1 addition & 4 deletions src/services/carrier_metadata_service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,7 @@ export default (easypostClient: EasyPostClient) =>
* @param {Array} type - List of types in string
* @returns {Object[]} - List of carrier metadata
*/
static async retrieve(
carriers: string[] | null = null,
types: string[] | null = null,
): Promise<CarrierMetadata[]> {
static async retrieve(carriers: string[] | null = null, types: string[] | null = null): Promise<CarrierMetadata[]> {
const url = 'metadata/carriers';
const params = {
...(carriers && carriers.length > 0 && { carriers: carriers.join(',') }),
Expand Down
5 changes: 1 addition & 4 deletions src/services/claim_service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,10 +51,7 @@ export default (easypostClient: EasyPostClient) =>
* @param {Number} pageSize The number of records to return on each page
* @returns {EasyPostObject|Promise<never>} The retrieved {@link EasyPostObject}-based class instance, or a `Promise` that rejects with an error.
*/
static async getNextPage(
claims: ClaimCollection,
pageSize: number | null = null,
): Promise<ClaimListResponse> {
static async getNextPage(claims: ClaimCollection, pageSize: number | null = null): Promise<ClaimListResponse> {
const url = 'claims';
return this._getNextPage(url, 'claims', claims, pageSize);
}
Expand Down
4 changes: 1 addition & 3 deletions src/services/embeddable_service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,7 @@ export default (easypostClient: EasyPostClient) =>
* @param {Object} [params] - The parameters to create a session from.
* @returns {Object} - An object containing the created session.
*/
static async createSession(
params: EmbeddablesSessionCreateParameters = {},
): Promise<IEmbeddablesSession> {
static async createSession(params: EmbeddablesSessionCreateParameters = {}): Promise<IEmbeddablesSession> {
const url = 'embeddables/session';

try {
Expand Down
5 changes: 1 addition & 4 deletions src/services/event_service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,10 +67,7 @@ export default (easypostClient: EasyPostClient) =>
* @param {Number} pageSize The number of records to return on each page
* @returns {EasyPostObject|Promise<never>} The retrieved {@link EasyPostObject}-based class instance, or a `Promise` that rejects with an error.
*/
static async getNextPage(
events: EventCollection,
pageSize: number | null = null,
): Promise<EventListResponse> {
static async getNextPage(events: EventCollection, pageSize: number | null = null): Promise<EventListResponse> {
const url = 'events';
return this._getNextPage(url, 'events', events, pageSize);
}
Expand Down
5 changes: 1 addition & 4 deletions src/services/pickup_service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,10 +101,7 @@ export default (easypostClient: EasyPostClient) =>
* @param {Number} pageSize The number of records to return on each page
* @returns {EasyPostObject|Promise<never>} The retrieved {@link EasyPostObject}-based class instance, or a `Promise` that rejects with an error.
*/
static async getNextPage(
pickups: PickupCollection,
pageSize: number | null = null,
): Promise<PickupListResponse> {
static async getNextPage(pickups: PickupCollection, pageSize: number | null = null): Promise<PickupListResponse> {
const url = 'pickups';
return this._getNextPage(url, 'pickups', pickups, pageSize);
}
Expand Down
5 changes: 1 addition & 4 deletions src/services/refund_service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,10 +49,7 @@ export default (easypostClient: EasyPostClient) =>
* @param {Number} pageSize The number of records to return on each page
* @returns {EasyPostObject|Promise<never>} The retrieved {@link EasyPostObject}-based class instance, or a `Promise` that rejects with an error.
*/
static async getNextPage(
refunds: RefundCollection,
pageSize: number | null = null,
): Promise<RefundListResponse> {
static async getNextPage(refunds: RefundCollection, pageSize: number | null = null): Promise<RefundListResponse> {
const url = 'refunds';
return this._getNextPage(url, 'refunds', refunds, pageSize);
}
Expand Down
5 changes: 1 addition & 4 deletions src/services/report_service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,10 +64,7 @@ export default (easypostClient: EasyPostClient) =>
* @param {Number} pageSize The number of records to return on each page
* @returns {EasyPostObject|Promise<never>} The retrieved {@link EasyPostObject}-based class instance, or a `Promise` that rejects with an error.
*/
static async getNextPage(
reports: ReportCollection,
pageSize: number | null = null,
): Promise<ReportListResponse> {
static async getNextPage(reports: ReportCollection, pageSize: number | null = null): Promise<ReportListResponse> {
const firstReport = reports.reports?.[0] as { _params?: { type?: string } } | undefined;
const url = `reports/${firstReport?._params?.type || ''}`;
return this._getNextPage(url, 'reports', reports, pageSize);
Expand Down
23 changes: 4 additions & 19 deletions src/services/shipment_service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,12 +27,7 @@ type ShipmentCreateParameters = Record<string, unknown> & {
from_address?: AddressCreateParameters | Address | string | null;
parcel?: ParcelCreateParameters | Parcel | string | null;
carrier_accounts?: string[] | null;
customs_info?:
| CustomsInfo
| CustomsInfo[]
| CustomsInfoCreateParameters
| CustomsInfoCreateParameters[]
| null;
customs_info?: CustomsInfo | CustomsInfo[] | CustomsInfoCreateParameters | CustomsInfoCreateParameters[] | null;
tax_identifiers?: Array<ShipmentTaxIdentifier | null | undefined> | null;
options?: Record<string, unknown> | null;
line_items?: ShipmentLineItem[] | null;
Expand Down Expand Up @@ -252,11 +247,7 @@ export default (easypostClient: EasyPostClient) =>
deliveryAccuracy: string,
): Promise<ReturnType<typeof Constants.Utils.getLowestSmartRate>> {
const smartRates = (await this.getSmartRates(id)) as SmartRate[];
return Constants.Utils.getLowestSmartRate(
smartRates,
deliveryDays,
deliveryAccuracy.toLowerCase(),
);
return Constants.Utils.getLowestSmartRate(smartRates, deliveryDays, deliveryAccuracy.toLowerCase());
}

/**
Expand All @@ -277,10 +268,7 @@ export default (easypostClient: EasyPostClient) =>
* @param {Number} pageSize The number of records to return on each page
* @returns {EasyPostObject|Promise<never>} The retrieved {@link EasyPostObject}-based class instance, or a `Promise` that rejects with an error.
*/
static async getNextPage(
shipments: ShipmentCollection,
pageSize?: number,
): Promise<ShipmentListResponse> {
static async getNextPage(shipments: ShipmentCollection, pageSize?: number): Promise<ShipmentListResponse> {
const url = 'shipments';

return this._getNextPage(url, 'shipments', shipments, pageSize);
Expand Down Expand Up @@ -329,10 +317,7 @@ export default (easypostClient: EasyPostClient) =>
* @param desiredDeliveryDate - The desired delivery date for the shipment.
* @returns {Array} - An array of the recommended ship date and rates.
*/
static async recommendShipDate(
id: string,
desiredDeliveryDate: string,
): Promise<ShipmentSmartRateResponse> {
static async recommendShipDate(id: string, desiredDeliveryDate: string): Promise<ShipmentSmartRateResponse> {
const url = `shipments/${id}/smartrate/precision_shipping`;

const wrappedParams = {
Expand Down
9 changes: 2 additions & 7 deletions src/services/user_service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -187,8 +187,7 @@ export default (easypostClient: EasyPostClient) =>
throw new EndOfPaginationError();
}

const firstObjectParams =
(collectionArray[0]?._params as Record<string, unknown> | undefined) ?? {};
const firstObjectParams = (collectionArray[0]?._params as Record<string, unknown> | undefined) ?? {};
const defaultParams = collection._params ?? firstObjectParams;

const params = {
Expand All @@ -199,11 +198,7 @@ export default (easypostClient: EasyPostClient) =>

const response = (await this._all(url, params)) as Record<string, unknown>;
const responseCollection = response[key] as Array<Record<string, unknown>> | undefined;
if (
response == undefined ||
responseCollection == undefined ||
responseCollection.length == 0
) {
if (response == undefined || responseCollection == undefined || responseCollection.length == 0) {
throw new EndOfPaginationError();
}

Expand Down
Loading