You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
53 lines
1.7 KiB
53 lines
1.7 KiB
import { Reflect } from '../../../lib/src/external/reflect.ts'
|
|
import { Collection } from '../../../lib/src/collection/Collection.ts'
|
|
import { logger } from '../../../lib/src/service/logging/global.ts'
|
|
import {Type} from '../db/types.ts'
|
|
import {Model} from "./Model.ts";
|
|
|
|
export const DATON_ORM_MODEL_FIELDS_METADATA_KEY = 'daton:orm:modelFields.ts'
|
|
|
|
export function get_fields_meta(model: any): Collection<ModelField> {
|
|
const fields = Reflect.getMetadata(DATON_ORM_MODEL_FIELDS_METADATA_KEY, model.constructor)
|
|
if ( !(fields instanceof Collection) ) {
|
|
return new Collection<ModelField>()
|
|
}
|
|
|
|
return fields as Collection<ModelField>
|
|
}
|
|
|
|
export function set_model_fields_meta(model: any, fields: Collection<ModelField>) {
|
|
Reflect.defineMetadata(DATON_ORM_MODEL_FIELDS_METADATA_KEY, fields, model.constructor)
|
|
}
|
|
|
|
export interface ModelField {
|
|
database_key: string,
|
|
model_key: string | symbol,
|
|
type: any,
|
|
}
|
|
|
|
export function Field(type: Type, database_key?: string): PropertyDecorator {
|
|
return (target, model_key) => {
|
|
if ( !database_key ) database_key = String(model_key)
|
|
const fields = get_fields_meta(target)
|
|
|
|
logger.debug(`Registering field mapping ${database_key} => ${String(model_key)} as ${type} for model.`)
|
|
logger.verbose(target)
|
|
|
|
const existing_field = fields.firstWhere('model_key', '=', model_key)
|
|
if ( existing_field ) {
|
|
existing_field.database_key = database_key
|
|
existing_field.type = type
|
|
|
|
return set_model_fields_meta(target, fields)
|
|
}
|
|
|
|
fields.push({
|
|
database_key,
|
|
model_key,
|
|
type,
|
|
})
|
|
|
|
set_model_fields_meta(target, fields)
|
|
}
|
|
}
|