Commit fb70fb1e authored by nanahira's avatar nanahira

update StringIdBase and DateColumn parser

parent 128a4577
......@@ -7,7 +7,7 @@ import {
NotWritable,
StringColumn,
} from '../decorators';
import { IsNotEmpty } from 'class-validator';
import { IsNotEmpty, IsString } from 'class-validator';
import { MergePropertyDecorators } from 'nesties';
export interface IdOptions {
......@@ -38,7 +38,7 @@ export function IdBase(idOptions: IdOptions = {}) {
}
export interface StringIdOptions extends IdOptions {
length: number;
length?: number;
uuid?: boolean;
}
......@@ -56,18 +56,21 @@ export function StringIdBase(idOptions: StringIdOptions) {
}
};
const decs = [
NotChangeable(),
StringColumn(idOptions.length, {
StringColumn(idOptions.length || (idOptions.uuid ? 36 : 255), {
required: !idOptions.uuid,
description: idOptions.description,
columnExtras: { primary: true, nullable: false },
}),
Reflect.metadata('design:type', String),
IsNotEmpty(),
...(idOptions.uuid ? [
Generated('uuid'),
NotWritable(),
] : [
IsString(),
IsNotEmpty(),
NotChangeable(),
])
];
if (idOptions.uuid) {
decs.push(Generated('uuid'));
}
const dec = MergePropertyDecorators(decs);
dec(cl.prototype, 'id');
return cl;
......
......@@ -144,13 +144,23 @@ export const DateColumn = (
IsDate(),
Transform(
(v) => {
if (v.value == null) return v.value;
if (v.value instanceof Date) return v.value;
if (typeof v.value === 'number') return new Date(v.value * 1000);
if (typeof v.value === 'string' && v.value.match(/^\d+$/)) {
return new Date(parseInt(v.value, 10) * 1000);
const value = v.value;
if (value == null || value instanceof Date) return value;
const timestampToDate = (t: number, isSeconds: boolean) =>
new Date(isSeconds ? t * 1000 : t);
if (typeof value === 'number') {
const isSeconds = !Number.isInteger(value) || value < 1e12;
return timestampToDate(value, isSeconds);
}
return new Date(v.value);
if (typeof value === 'string' && /^\d+(\.\d+)?$/.test(value)) {
const isSeconds = value.includes('.') || parseFloat(value) < 1e12;
return timestampToDate(parseFloat(value), isSeconds);
}
return new Date(value); // fallback to native parser
},
{
toClassOnly: true,
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment