UNPKG

@dgac/nmb2b-client

Version:

EUROCONTROL Network Manager B2B SOAP client

71 lines (69 loc) 2.16 kB
import { types } from "./types.mjs"; import { evolve, identity, map, piped } from "remeda"; //#region src/utils/transformers/serializer.ts function prepareSerializer(schema) { const transformer = prepareTransformer(schema); return piped(reorderKeys(schema), transformer ? evolve(transformer) : identity); } function reduceXSDType(str) { return str.split("|")[0]; } function prepareTransformer(schema) { return Object.keys(schema).reduce((prev, curr) => { let key = curr; let isArray = false; /** * If the current key marks an array, we need to map over the values instead of just trying * to transform the value. * * We also need to assign the correct key to the transformer. */ if (curr.endsWith("[]")) { key = curr.slice(0, -2); isArray = true; } if (typeof schema[curr] === "string") { const type = reduceXSDType(schema[curr]); if (types[type]?.input) { const transformer = types[type].input; return { ...prev, [key]: isArray ? map(transformer) : transformer }; } } else if (typeof schema[curr] === "object") { const subItem = prepareTransformer(schema[curr]); if (subItem) return { ...prev, [key]: isArray ? map(evolve(subItem)) : subItem }; } return prev; }, null); } function reorderKeys(schema) { return (obj) => { return Object.keys(schema).reduce((prev, curr) => { const lookupKey = curr.replace(/\[\]$/, ""); const isArrayExpected = curr.endsWith("[]"); if (!(lookupKey in obj)) return prev; const currSchema = schema[curr]; if (typeof currSchema === "string") { prev[lookupKey] = obj[lookupKey]; return prev; } if (typeof currSchema === "object") { if (Object.keys(currSchema).filter((k) => k !== "targetNSAlias" && k !== "targetNamespace").length) { prev[lookupKey] = isArrayExpected && obj[lookupKey] && Array.isArray(obj[lookupKey]) ? obj[lookupKey].map(reorderKeys(currSchema)) : reorderKeys(currSchema)(obj[lookupKey]); return prev; } prev[lookupKey] = obj[lookupKey]; return prev; } return prev; }, {}); }; } //#endregion export { prepareSerializer }; //# sourceMappingURL=serializer.mjs.map