@nestjs/common
Version:
Decorators, pipes, exceptions and utilities for NestJS applications: @Controller(), @Injectable(), @Body(), ValidationPipe, HttpException and more.
157 lines (156 loc) • 6.16 kB
JavaScript
import { __decorate, __metadata, __param } from "tslib";
import { Injectable } from '../decorators/core/injectable.decorator.js';
import { Optional } from '../decorators/core/optional.decorator.js';
import { HttpStatus } from '../enums/http-status.enum.js';
import { HttpErrorByCode, } from '../utils/http-error-by-code.util.js';
import { isNil, isNumber, isString } from '../utils/shared.utils.js';
const DAYS_IN_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
const MONTH_NAMES = [
'jan',
'feb',
'mar',
'apr',
'may',
'jun',
'jul',
'aug',
'sep',
'oct',
'nov',
'dec',
];
// As in `new Date()`, the parts of a date may be separated by any run of
// spaces, commas, dots, slashes and dashes ("2024 02 30", "02,30,2024",
// "Feb.30.2024"), and a numeric date may follow a weekday ("Fri 02/30/2024").
const NAMED_MONTH_DATE_PATTERNS = [
// "Feb 30, 2024", "Thu Feb 30 2024 10:00:00 GMT+0300", "Feb-30-2024",
// "Feb 30, 24"
/^\s*(?:[a-z]+,?\s+)?(?<month>[a-z]{3,})\.?[\s,./-]+(?<day>\d{1,2})[\s,./-]+(?<year>\d{4}|\d{2}(?!:))(?!\d)/i,
// "30 Feb 2024", "Thu, 30 Feb 2024 10:00:00 GMT", "30-Feb-2024", "30-Feb-24"
/^\s*(?:[a-z]+,?\s+)?(?<day>\d{1,2})[\s,./-]+(?<month>[a-z]{3,})\.?[\s,./-]+(?<year>\d{4}|\d{2}(?!:))(?!\d)/i,
// "2024 Feb 30", "2024-Feb-30"
/^\s*(?<year>\d{4})[\s,./-]+(?<month>[a-z]{3,})\.?[\s,./-]+(?<day>\d{1,2})(?!\d)/i,
];
// "2024-02-30", "2024 02 30", "Fri, 2024/02/30", "+002024-02-30"
const YEAR_FIRST_DATE_PATTERN = /^\s*(?:(?:sun|mon|tue|wed|thu|fri|sat)[a-z]*,?\s+)?([+-]\d{6}|\d{4})[\s,./-]+(\d{1,2})[\s,./-]+(\d{1,2})(?!\d)/i;
// "02/30/2024", "02,30,2024", "Fri 02/30/2024", "2.30.24"
const MONTH_FIRST_DATE_PATTERN = /^\s*(?:(?:sun|mon|tue|wed|thu|fri|sat)[a-z]*,?\s+)?(\d{1,2})[\s,./-]+(\d{1,2})[\s,./-]+(\d{4}|\d{2}(?!:))(?!\d)/i;
/**
* Reads a year as `new Date()` does, where a two-digit year below 50 is in
* the 2000s ("2/29/24" is in 2024) and any other in the 1900s. Two digits
* followed by ":" are the hour of a time ("Feb 29 10:00 2024"), not a year.
*/
function toFullYear(year) {
const value = Number(year);
if (year.length !== 2) {
return value;
}
return value < 50 ? 2000 + value : 1900 + value;
}
/**
* @publicApi
*/
let ParseDatePipe = class ParseDatePipe {
options;
exceptionFactory;
constructor(options = {}) {
this.options = options;
const { exceptionFactory, errorHttpStatusCode = HttpStatus.BAD_REQUEST } = options;
this.exceptionFactory =
exceptionFactory ||
(error => new HttpErrorByCode[errorHttpStatusCode](error));
}
/**
* Method that accesses and performs optional transformation on argument for
* in-flight requests.
*
* @param value currently processed route argument
* @param metadata contains metadata about the currently processed route argument
*/
transform(value) {
if (isNil(value)) {
// `default` applies to nil values whether or not `optional` is set.
if (this.options.default) {
return this.options.default();
}
if (this.options.optional) {
return value;
}
}
if (isNil(value) || value === '') {
throw this.exceptionFactory('Validation failed (no Date provided)');
}
const transformedValue = isString(value) || isNumber(value) || value instanceof Date
? new Date(value)
: new Date(NaN);
if (isNaN(transformedValue.getTime()) ||
(isString(value) && this.hasDayPastMonthEnd(value))) {
throw this.exceptionFactory('Validation failed (invalid date format)');
}
return transformedValue;
}
/**
* `new Date()` rolls a day past the end of its month into the next month
* ("2024-02-30" becomes March 1), so date strings are checked against
* the length of their month.
*/
hasDayPastMonthEnd(value) {
let year;
let month;
let day;
const isoMatch = YEAR_FIRST_DATE_PATTERN.exec(value);
if (isoMatch) {
year = Number(isoMatch[1]);
month = Number(isoMatch[2]);
day = Number(isoMatch[3]);
}
else {
const usMatch = MONTH_FIRST_DATE_PATTERN.exec(value);
if (usMatch) {
month = Number(usMatch[1]);
day = Number(usMatch[2]);
year = toFullYear(usMatch[3]);
}
else {
const namedMatch = this.matchNamedMonthDate(value);
if (!namedMatch) {
return false;
}
[year, month, day] = namedMatch;
}
}
// `new Date()` doesn't read a number above 31 as a day ("99-Jan-20" is
// January 20, 1999), so such a reading is left to it
if (day > 31) {
return false;
}
const isLeapYear = (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
const daysInMonth = month === 2 && isLeapYear ? 29 : DAYS_IN_MONTH[month - 1];
return daysInMonth !== undefined && day > daysInMonth;
}
/**
* Reads the year, month and day of a date whose month is a name ("Feb 30,
* 2024", "30 Feb 2024", "2024-Feb-30"), optionally after a weekday ("Thu,
* 30 Feb 2024 10:00:00 GMT"). As in `new Date()`, a month is named by its
* first three letters.
*/
matchNamedMonthDate(value) {
for (const pattern of NAMED_MONTH_DATE_PATTERNS) {
const groups = pattern.exec(value)?.groups;
if (!groups) {
continue;
}
const month = MONTH_NAMES.indexOf(groups.month.slice(0, 3).toLowerCase()) + 1;
if (month > 0) {
return [toFullYear(groups.year), month, Number(groups.day)];
}
}
return undefined;
}
};
ParseDatePipe = __decorate([
Injectable(),
__param(0, Optional()),
__metadata("design:paramtypes", [Object])
], ParseDatePipe);
export { ParseDatePipe };