import { AUTO_GENERATE_ATTRIBUTE_STRATEGY } from '@typedorm/common' ; import KSUID from 'ksuid' ; import { v4 } from 'uuid' ; import { BaseAttributeMetadata , BaseAttributeMetadataOptions , } from './base-attribute-metadata' ; export const IsAutoGeneratedAttributeMetadata = ( attr ) : attr is AutoGeneratedAttributeMetadata => ! ! attr . strategy ; export interface AutoGeneratedAttributeMetadataOptions extends BaseAttributeMetadataOptions { strategy : AUTO_GENERATE_ATTRIBUTE_STRATEGY ; autoUpdate ? : boolean ; } export class AutoGeneratedAttributeMetadata extends BaseAttributeMetadata { readonly strategy : AUTO_GENERATE_ATTRIBUTE_STRATEGY ; readonly autoUpdate : boolean ; readonly unique : boolean ; constructor ( options ) { const { strategy , autoUpdate } = options ; super ( options ) ; this . autoUpdate = ! ! autoUpdate ; this . strategy = strategy ; } get value ( ) { return this . autoGenerateValue ( this . strategy ) ; } autoGenerateValue ( strategy ) { switch ( strategy ) { case AUTO_GENERATE_ATTRIBUTE_STRATEGY . UUID4 : { return v4 ( ) ; } case AUTO_GENERATE_ATTRIBUTE_STRATEGY . KSUID : { return KSUID . randomSync ( new Date ( ) ) . string ; } case AUTO_GENERATE_ATTRIBUTE_STRATEGY . ISO_DATE : { return new Date ( ) . toISOString ( ) ; } case AUTO_GENERATE_ATTRIBUTE_STRATEGY . EPOCH_DATE : { return Math . ceil ( new Date ( ) . valueOf ( ) / 1000 ) ; } default : { throw new Error ( 'Unknown attribute strategy.' ) ; } } } }