@gulujs/toml
Version:
TOML parser and serializer
73 lines (72 loc) • 2.71 kB
JavaScript
import { INVALID_DATETIME_MESSAGE, InvalidValueError } from '../errors/index.js';
import { DateTimeType, TomlDate } from '../date.js';
export class DatetimeConverter {
constructor(options) {
this.defaultDateTimeType = options?.defaultDateTimeType || DateTimeType.LocalDateTime;
this.utcOffset = options?.utcOffset;
}
convertStringToJsValue(str, options) {
let date;
switch (options.type) {
case DateTimeType.OffsetDateTime:
date = TomlDate.ofOffsetDateTime(str);
break;
case DateTimeType.LocalDateTime:
date = TomlDate.ofLocalDateTime(str);
break;
case DateTimeType.LocalDate:
date = TomlDate.ofLocalDate(str);
break;
case DateTimeType.LocalTime:
date = TomlDate.ofLocalTime(str);
break;
default:
throw new RangeError('The `type` must be a valid value for `DateTimeType`');
}
if (!date.isValid) {
throw new InvalidValueError(INVALID_DATETIME_MESSAGE(str));
}
return date;
}
isJsValue(value) {
return value instanceof Date;
}
convertJsValueToString(value, options) {
const type = options.type || this.defaultDateTimeType;
if (value instanceof TomlDate) {
return value.toString();
}
let rawDate;
if (value instanceof Date) {
rawDate = value;
}
else if (this.isDateLike(value)) {
rawDate = value.valueOf();
}
if (typeof rawDate !== 'undefined') {
let date;
switch (type) {
case DateTimeType.OffsetDateTime:
date = TomlDate.ofOffsetDateTime(rawDate, this.utcOffset);
break;
case DateTimeType.LocalDateTime:
date = TomlDate.ofLocalDateTime(rawDate);
break;
case DateTimeType.LocalDate:
date = TomlDate.ofLocalDate(rawDate);
break;
case DateTimeType.LocalTime:
date = TomlDate.ofLocalTime(rawDate);
break;
default:
throw new RangeError('The `type` must be a valid value for `DateTimeType`');
}
return date.toString();
}
// eslint-disable-next-line @typescript-eslint/no-base-to-string
throw new TypeError(`DateTime "${value}" is not an expected value`);
}
isDateLike(value) {
return !!value && typeof value.valueOf === 'function';
}
}