110 lines
4.1 KiB
JavaScript
110 lines
4.1 KiB
JavaScript
'use strict';
|
|
|
|
const crypto = require('crypto');
|
|
const config = require('./config');
|
|
|
|
// Adds the key and the usual headers to every request made with z.request.
|
|
const addHeaders = (request, z, bundle) => {
|
|
request.headers = request.headers || {};
|
|
const key = bundle && bundle.authData ? String(bundle.authData.apiKey || '').trim() : '';
|
|
if (key && !request.headers.Authorization) {
|
|
request.headers.Authorization = 'Bearer ' + key;
|
|
}
|
|
request.headers.Accept = 'application/json';
|
|
request.headers['Accept-Language'] = 'en';
|
|
request.headers['User-Agent'] = config.USER_AGENT;
|
|
return request;
|
|
};
|
|
|
|
const parseBody = (response) => {
|
|
if (response.data !== undefined && response.data !== null && typeof response.data === 'object') {
|
|
return response.data;
|
|
}
|
|
try {
|
|
return JSON.parse(response.content || '{}');
|
|
} catch (e) {
|
|
return {};
|
|
}
|
|
};
|
|
|
|
// Turns API errors into clear messages. The key is never part of a message.
|
|
const handleErrors = (response, z) => {
|
|
if (response.status < 400) {
|
|
return response;
|
|
}
|
|
const body = parseBody(response);
|
|
const err = body.error || {};
|
|
const code = err.code || 'http_' + response.status;
|
|
const details = err.details || {};
|
|
const apiMessage = err.message || 'The API answered with status ' + response.status + '.';
|
|
const ref = err.correlation_id ? ' (reference ' + err.correlation_id + ')' : '';
|
|
|
|
if (response.status === 401) {
|
|
const Expired = z.errors.ExpiredAuthError || z.errors.Error;
|
|
throw new Expired(
|
|
'The API key is not valid, was revoked or has expired. Create a new one in the API Center: ' + config.API_CENTER_URL
|
|
);
|
|
}
|
|
if (response.status === 429) {
|
|
const header = response.getHeader ? response.getHeader('retry-after') : null;
|
|
const wait = parseInt(header || details.retry_after || '60', 10) || 60;
|
|
throw new z.errors.ThrottledError('Too many requests. Wait ' + wait + ' seconds and try again.' + ref, wait);
|
|
}
|
|
if (response.status === 402) {
|
|
const funds = details.add_funds_url ? ' Add funds: ' + details.add_funds_url : '';
|
|
throw new z.errors.Error('Not enough credit, nothing was charged. ' + apiMessage + funds + ref, code, 402);
|
|
}
|
|
if (response.status === 403 && code === 'insufficient_scope') {
|
|
throw new z.errors.Error(
|
|
'This API key does not have the permission this step needs. ' + apiMessage +
|
|
' Create a key with it in the API Center: ' + config.API_CENTER_URL + ref,
|
|
code,
|
|
403
|
|
);
|
|
}
|
|
const reason = details.reason ? ' [' + details.reason + ']' : '';
|
|
throw new z.errors.Error(apiMessage + reason + ref, code, response.status);
|
|
};
|
|
|
|
// Calls the API and returns the "data" part of the answer (or the whole body when there is none).
|
|
const api = async (z, options) => {
|
|
const request = {
|
|
method: options.method || 'GET',
|
|
url: config.API_URL + options.path,
|
|
params: options.params,
|
|
headers: {},
|
|
};
|
|
if (options.body !== undefined) {
|
|
request.body = options.body;
|
|
request.headers['Content-Type'] = 'application/json';
|
|
}
|
|
if (options.idempotent) {
|
|
request.headers['Idempotency-Key'] = options.idempotencyKey || crypto.randomUUID();
|
|
}
|
|
const response = await z.request(request);
|
|
const body = parseBody(response);
|
|
return options.raw ? body : body.data !== undefined ? body.data : body;
|
|
};
|
|
|
|
// Removes empty values so optional fields are not sent.
|
|
const compact = (obj) => {
|
|
const out = {};
|
|
Object.keys(obj).forEach((k) => {
|
|
const v = obj[k];
|
|
if (v === undefined || v === null || v === '') return;
|
|
if (Array.isArray(v) && v.length === 0) return;
|
|
if (typeof v === 'object' && !Array.isArray(v) && Object.keys(v).length === 0) return;
|
|
out[k] = v;
|
|
});
|
|
return out;
|
|
};
|
|
|
|
// Accepts "a@x.com, b@y.com", an array, or a Zapier line-item list.
|
|
const toList = (value) => {
|
|
if (value === undefined || value === null || value === '') return undefined;
|
|
const items = Array.isArray(value) ? value : String(value).split(',');
|
|
const list = items.map((s) => String(s).trim()).filter(Boolean);
|
|
return list.length ? list : undefined;
|
|
};
|
|
|
|
module.exports = { addHeaders, handleErrors, api, compact, toList };
|