mpp-sdk
Version:
SDK to talk to the Memento Payments Platform
93 lines (92 loc) • 3.26 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
exports.filtersToParams = exports.headers = exports.uuidv4 = exports.isIdempotent = void 0;
const version_1 = require("../version");
const FILTER_DELIMITER = ":";
const FILTER_VALUE_DELIMITER = "|";
const NON_IDEMPOTENT_HTTP_METHODS = new Set(["post", "patch"]);
const isIdempotent = (method) => !NON_IDEMPOTENT_HTTP_METHODS.has(method);
exports.isIdempotent = isIdempotent;
const uuidv4 = () => {
return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (c) {
var r = (Math.random() * 16) | 0, v = c == "x" ? r : (r & 0x3) | 0x8;
return v.toString(16);
});
};
exports.uuidv4 = uuidv4;
const headers = (axiosConfig, mppConfig) => {
var _a;
var headers = {
"Content-Type": "application/json; charset=utf-8",
"User-Agent": `${mppConfig.appName}/${mppConfig.appVersion} (JSSDK ${version_1.LIB_VERSION})`,
};
if (mppConfig.projectId) {
headers["Project-ID"] = mppConfig.projectId;
}
if (mppConfig.overwriteLocale !== undefined) {
headers["Accept-Language"] = mppConfig.overwriteLocale;
}
// Only set idempotency header when using non-idempotent methods.
const method = ((_a = axiosConfig.method) === null || _a === void 0 ? void 0 : _a.toLowerCase()) || "";
if (!(0, exports.isIdempotent)(method)) {
headers["Idempotency-Key"] = (0, exports.uuidv4)();
}
return headers;
};
exports.headers = headers;
const filtersToParams = (options) => {
const params = {};
if (options.page) {
params["page"] = options.page;
}
if (options.limit) {
params["limit"] = options.limit;
}
if (options.sort) {
const parts = [];
for (var s of options.sort) {
if (s.length !== 2) {
throw new Error("Invalid sort definition");
}
parts.push(s[0] + FILTER_DELIMITER + s[1]);
}
params["sort"] = parts.join(FILTER_VALUE_DELIMITER);
}
if (options.filter) {
// Go through all the filters and add to query params map
const parts = [];
const filterKeys = Object.keys(options.filter);
const handleFilterOp = (key, opObj) => {
if (!opObj) {
return;
}
// Should always get a single op
const [op] = Object.keys(opObj);
// Serialize to string
let x;
const values = opObj[op];
if (Array.isArray(values)) {
x = values.join(FILTER_DELIMITER);
}
else {
x = values;
}
// Compile the parts
parts.push(`${key}${FILTER_DELIMITER}${op}${FILTER_DELIMITER}${x}`);
};
const handleFilter = (filter) => {
for (const key of filterKeys) {
handleFilterOp(key, filter[key]);
}
};
if (Array.isArray(options.filter)) {
options.filter.forEach(handleFilter);
}
else {
handleFilter(options.filter);
}
params["filter"] = parts.join(FILTER_VALUE_DELIMITER);
}
return params;
};
exports.filtersToParams = filtersToParams;
;