@odata2ts/converter-common
Version:
Luxon based odata2ts compatible converters for date and time related OData types
67 lines • 1.95 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.simpleTimeConverter = exports.NOOP_TIME = void 0;
const PERIOD_PREFIX = "PT";
exports.NOOP_TIME = "PT0H0M";
const TIME_TYPE = [
{
prop: "hour",
pattern: /T.*?(\d+)H/,
suffix: "H",
},
{
prop: "minute",
pattern: /T.*?(\d+)M/,
suffix: "M",
},
{
prop: "second",
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.simpleTimeConverter = {
id: "simpleTimeConverter",
from: "Edm.Time",
to: "@odata2ts/converter-common.SimpleTime",
convertFrom: function (value) {
if (typeof value !== "string") {
return value;
}
// invalid time returns undefined
if (!value || !value.startsWith(PERIOD_PREFIX)) {
return undefined;
}
return TIME_TYPE.reduce((duration, typeInfo) => {
duration[typeInfo.prop] = getSafeValue(value, typeInfo.pattern, typeInfo.allowFloat);
return duration;
}, { hour: 0, minute: 0, second: 0 });
},
convertTo: function (value) {
if (!value) {
return value;
}
const time = TIME_TYPE.reduce((result, current) => {
return result + format(value[current.prop], current.suffix);
}, "");
// time is only valid if hour and minute part is specified
if (!time) {
return exports.NOOP_TIME;
}
return PERIOD_PREFIX + time;
},
};
//# sourceMappingURL=SimpleTimeConverter.js.map