UNPKG

@odata2ts/converter-common

Version:

Luxon based odata2ts compatible converters for date and time related OData types

87 lines 2.56 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.simpleDurationConverter = exports.NOOP_PERIOD = void 0; const PERIOD_PREFIX = "P"; const TIME_SEPARATOR = "T"; exports.NOOP_PERIOD = "PT0H"; const DURATION_TYPE = [ { prop: "years", pattern: /^[^T]+?(\d+)Y/, suffix: "Y", }, { prop: "months", pattern: /^[^T]+?(\d+)M/, suffix: "M", }, { prop: "days", pattern: /^[^T]+?(\d+)D/, suffix: "D", }, { prop: "hours", pattern: /T.*?(\d+)H/, suffix: "H", }, { prop: "minutes", pattern: /T.*?(\d+)M/, suffix: "M", }, { prop: "seconds", pattern: /T.*?([\d.]+)S/, suffix: "S", allowFloat: true, }, ]; function getSafeValue(value, regExp, allowFloat) { const result = value.match(regExp); // prettier-ignore return !result || result.length !== 2 ? 0 : allowFloat ? parseFloat(result[1]) : parseInt(result[1]); } function format(value, suffix) { return value ? value + suffix : ""; } exports.simpleDurationConverter = { id: "simpleDurationConverter", from: "Edm.Duration", to: "@odata2ts/converter-common.SimpleDuration", convertFrom: function (value) { if (typeof value !== "string") { return value; } // invalid duration returns undefined if (!value || !value.startsWith(PERIOD_PREFIX) || value.match(/^[^T]+(H|S)/)) { return undefined; } return DURATION_TYPE.reduce((duration, typeInfo) => { duration[typeInfo.prop] = getSafeValue(value, typeInfo.pattern, typeInfo.allowFloat); return duration; }, {}); }, convertTo: function (value) { if (!value) { return value; } const timeIndex = 3; const date = DURATION_TYPE.slice(0, timeIndex).reduce((result, current) => { return result + format(value[current.prop], current.suffix); }, ""); const time = DURATION_TYPE.slice(timeIndex).reduce((result, current) => { return result + format(value[current.prop], current.suffix); }, ""); // duration is only valid if some part is specified, at least one if (!date && !time) { return exports.NOOP_PERIOD; } return PERIOD_PREFIX + date + (time ? TIME_SEPARATOR + time : ""); }, }; //# sourceMappingURL=SimpleDurationConverter.js.map