Presupuestador_web/shared/lib/contexts/common/domain/entities/UTCDateValue.ts

92 lines
2.6 KiB
TypeScript
Raw Normal View History

2024-04-23 15:29:38 +00:00
import Joi from "joi";
import { EmptyOr } from "../../../../utilities";
import { RuleValidator } from "../RuleValidator";
2024-05-26 17:09:43 +00:00
import { DomainError, handleDomainError } from "../errors";
2024-04-23 15:29:38 +00:00
import { Result } from "./Result";
import { IValueObjectOptions, ValueObject } from "./ValueObject";
export interface IDateValueOptions extends IValueObjectOptions {
dateFormat?: string;
}
export class UTCDateValue extends ValueObject<Date> {
2024-05-26 17:09:43 +00:00
protected static validate(value: EmptyOr<string>, options: IDateValueOptions) {
2024-04-23 15:29:38 +00:00
const ruleIsEmpty = RuleValidator.RULE_ALLOW_EMPTY.default(0);
const rulesIsDate = Joi.date()
//.format(String(options.dateFormat))
.label(String(options.label));
const rules = Joi.alternatives(ruleIsEmpty, rulesIsDate);
return RuleValidator.validate<string>(rules, value);
}
public static createCurrentDate() {
return Result.ok<UTCDateValue>(new UTCDateValue(new Date()));
}
2024-05-26 17:09:43 +00:00
public static create(value: EmptyOr<string>, options: IDateValueOptions = {}) {
2024-04-23 15:29:38 +00:00
const _options = {
...options,
dateFormat: options.dateFormat ? options.dateFormat : "YYYY-MM-DD",
label: options.label ? options.label : "date",
};
const validationResult = UTCDateValue.validate(value, _options);
if (validationResult.isFailure) {
2024-05-26 17:09:43 +00:00
return Result.fail(
handleDomainError(DomainError.INVALID_INPUT_DATA, validationResult.error.message, _options)
);
2024-04-23 15:29:38 +00:00
}
2024-05-26 17:09:43 +00:00
return Result.ok<UTCDateValue>(new UTCDateValue(new Date(validationResult.object)));
2024-04-23 15:29:38 +00:00
}
public isValid = (): boolean => {
return !isNaN(this.props.valueOf()) && this.props.valueOf() !== 0;
};
public isEmpty = (): boolean => {
return !this.isValid();
};
public toISO8601 = (): string => {
return this.isValid() ? this.props.toISOString() : "";
};
2024-07-10 09:53:13 +00:00
public toDateString = (): string => {
// Tue Jul 09 2024
return this.isValid() ? this.props.toDateString() : "";
};
public toLocaleDateString = (
locales?: Intl.LocalesArgument,
options?: Intl.DateTimeFormatOptions
): string => {
// DD/MM/YYYY
return this.isValid() ? this.props.toLocaleDateString(locales, options) : "";
};
public toLocaleTimeString = (): string => {
return this.isValid() ? this.props.toLocaleTimeString() : "";
};
2024-04-23 15:29:38 +00:00
public toString(): string {
2024-07-10 09:53:13 +00:00
// YYYY-MM-DD
2024-04-23 15:29:38 +00:00
if (!this.isEmpty()) {
const year = this.props.getFullYear();
const month = String(this.props.getMonth() + 1).padStart(2, "0");
const day = String(this.props.getDate()).padStart(2, "0");
return String(`${year}-${month}-${day}`);
}
return String("");
}
public toPrimitive(): string {
return this.toISO8601();
}
}