@shipengine/connect
Version:
The official developer tooling for building ShipEngine connect apps
82 lines • 3.06 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.createContextBuilder = void 0;
const tslib_1 = require("tslib");
const path_1 = require("path");
const fs_1 = require("fs");
const winston_1 = tslib_1.__importStar(require("winston"));
/** Predicate that returns true if the value is defined, false if not */
const valueIsUndefined = ([key, value]) => {
const isIncluded = value !== undefined;
console.log(`${isIncluded ? '✔️' : '❌'} ${key}`);
return isIncluded;
};
/** Build a lookup function to find values for a list of keys */
const buildLookup = (name, items, mapper) => (keys) => {
console.log(`Getting ${name} keys (${keys.length} total):`);
console.group();
try {
const things = keys.map((key) => {
const foundValue = items.find((item) => key === item.key)?.value;
const mappedValue = foundValue && mapper ? mapper(foundValue) : foundValue;
return [key, mappedValue];
});
const values = Object.fromEntries(things.filter(valueIsUndefined));
return Promise.resolve(values);
}
finally {
console.groupEnd();
}
};
const loadData = (basePath) => (dataType) => {
try {
const data = (0, fs_1.readFileSync)((0, path_1.resolve)(basePath, `${dataType}.json`));
const json = JSON.parse(data.toString());
return [dataType, json?.[dataType] || []];
}
catch (err) {
return [dataType, []];
}
};
const createContextBuilder = (basePath) => {
let zoneLookup;
const getZoneLookup = () => {
if (!zoneLookup) {
const zones = loadData(basePath)('zones')[1];
zoneLookup = buildLookup('zone', zones);
}
return zoneLookup;
};
const log = winston_1.default.createLogger({
transports: [
new winston_1.transports.Console({
level: 'debug',
format: winston_1.format.combine(winston_1.format.colorize(), winston_1.format.timestamp(), winston_1.format.metadata()),
}),
],
});
return (rateCard) => {
let dataLookup;
const getDataLookup = () => {
if (!dataLookup) {
const loadedData = Object.fromEntries(['rates', 'variables'].map(loadData((0, path_1.resolve)(basePath, rateCard.Id))));
dataLookup = {
rates: buildLookup('rate', loadedData.rates, (x) => ({
amount: +x,
currency: rateCard.Currency,
})),
variables: buildLookup('variables', loadedData.variables),
};
}
return dataLookup;
};
return {
getRates: (keys) => getDataLookup().rates(keys),
getVariables: (keys) => getDataLookup().variables(keys),
getZone: (keys) => getZoneLookup()(keys),
log,
};
};
};
exports.createContextBuilder = createContextBuilder;
//# sourceMappingURL=base-rate-context.js.map