@naturalcycles/nodejs-lib
Version:
Standard library for Node.js
72 lines • 2.95 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
const time_lib_1 = require("@naturalcycles/time-lib");
function stringExtensions(joi) {
return {
type: 'string',
base: joi.string(),
messages: {
'string.dateString': '"{{#label}}" must be an ISO8601 date (yyyy-mm-dd)',
'string.dateStringMin': '"{{#label}}" must be not earlier than {{#min}}',
'string.dateStringMax': '"{{#label}}" must be not later than {{#max}}',
'string.dateStringCalendarAccuracy': '"{{#label}}" must be a VALID calendar date',
},
rules: {
dateString: {
method(min, max) {
// tslint:disable-next-line:no-invalid-this
return this.$_addRule({
name: 'dateString',
args: { min, max },
});
},
args: [
{
name: 'min',
ref: true,
assert: v => typeof v === 'string',
message: 'must be a string',
},
{
name: 'max',
ref: true,
assert: v => typeof v === 'string',
message: 'must be a string',
},
],
validate(v, helpers, args) {
// console.log('dateString validate called', {v, args})
let err;
let { min, max } = args;
// Today allows +-14 hours gap to account for different timezones
if (max === 'today') {
max = time_lib_1.dayjs().add(14, 'hour').toISODate();
}
if (min === 'today') {
min = time_lib_1.dayjs().subtract(14, 'hour').toISODate();
}
// console.log('min/max', min, max)
const m = v.match(/^(\d{4})-(\d{2})-(\d{2})$/);
if (!m || m.length <= 1) {
err = 'string.dateString';
}
else if (min && v < min) {
err = 'string.dateStringMin';
}
else if (max && v > max) {
err = 'string.dateStringMax';
}
else if (!time_lib_1.dayjs(v).isValid()) {
err = 'string.dateStringCalendarAccuracy';
}
if (err) {
return helpers.error(err, args);
}
return v; // validation passed
},
},
},
};
}
exports.stringExtensions = stringExtensions;
//# sourceMappingURL=string.extensions.js.map