import { cloneDeep, mapValues, pick } from 'lodash'; import { CreateInfo, DefinationObject, ResultInfo, UpdateInfo, ValueType } from './types'; import { WithDefination } from './with-defination'; function isResultInfo(target: CreateInfo | ResultInfo): target is ResultInfo { return !!(target as ResultInfo).id; } export abstract class DefinationModel extends WithDefination { protected initInfo: CreateInfo | ResultInfo; protected info: ResultInfo; get id() { return this.info.id as string; } constructor(info: CreateInfo | ResultInfo) { super(); const initInfo = pick(info || {}, this.getAllKeys()) as CreateInfo | ResultInfo; this.initInfo = initInfo; if (isResultInfo(initInfo)) { this.info = cloneDeep(initInfo); } else { const resultInfo = Object.assign( {}, this.getDefaultInfo(), initInfo, this.createInnerInfo(), ) as ResultInfo; this.info = this.format(resultInfo); } this.validate(); } abstract createId(): string; isNew() { return !(this.initInfo as any).id; } update(info: Partial>) { const updateInfo = pick(info, this.getUpdateKeys()); Object.assign(this.info, this.format(updateInfo), { updateAt: new Date() }); this.validate(); } diff() { let hasDiff = false; const updateKeys = this.getUpdateKeys(); const diffs = updateKeys.reduce((ret, key) => { const newValue = this.info[key]; const oldValue = (this.initInfo as any)[key]; if (newValue !== oldValue) { hasDiff = true; ret[key] = newValue; } return ret; }, {} as Partial>); return hasDiff ? diffs : null; } validate() { // tobe override } toJSON(): ResultInfo { return cloneDeep(this.info); } protected format> | Partial> | Partial>>(info: K): K { const defination = this.getDefination(); return mapValues(info, (value, key) => { const definationProperty = defination[key]; if (value === null && !definationProperty.notNull) { return value; } const type = definationProperty.type; const initialValue = this.formatType(type, value); const formatArr = definationProperty.format || []; return formatArr.reduce((v: any, format) => format(v), initialValue) as any; }); } protected formatType(type: ValueType, value: any) { switch (type) { case 'number': return +value; case 'date': return new Date(value); case 'boolean': return +Boolean(value); default: return value; } } protected createInnerInfo() { return { id: this.createId(), createAt: new Date(), updateAt: new Date(), }; } }