61 lines
1.5 KiB
TypeScript
61 lines
1.5 KiB
TypeScript
import { prop, pre, modelOptions, plugin, getModelForClass as getModelForClassPub } from '@typegoose/typegoose';
|
|
import { TimeStamps } from '@typegoose/typegoose/lib/defaultClasses';
|
|
const mongooseLeanVirtuals = require('mongoose-lean-virtuals');
|
|
const mongooseLeanGetters = require('mongoose-lean-getters');
|
|
|
|
/**
|
|
* BaseModel
|
|
*/
|
|
@pre<BaseModel>('save', function(next) {
|
|
if (!this.createdAt || this.isNew) {
|
|
this.createdAt = this.updatedAt = new Date();
|
|
} else {
|
|
this.updatedAt = new Date();
|
|
}
|
|
next();
|
|
})
|
|
|
|
|
|
@modelOptions({schemaOptions: {id: false}})
|
|
@plugin(mongooseLeanVirtuals)
|
|
@plugin(mongooseLeanGetters)
|
|
export default class BaseModel extends TimeStamps {
|
|
|
|
_id?: string
|
|
|
|
@prop()
|
|
createdAt: Date
|
|
|
|
@prop()
|
|
updatedAt: Date
|
|
|
|
@prop()
|
|
createdBy: number; // 后台创建人
|
|
|
|
@prop()
|
|
updatedBy: number; // 最近更新人
|
|
}
|
|
|
|
|
|
function catchError(T) {
|
|
class T2 extends T {};
|
|
let names = Object.getOwnPropertyNames(T);
|
|
for(let name of names) {
|
|
if(typeof T[name] == 'function') {
|
|
T2[name] = async (...args: any) => {
|
|
// console.log('*****', args)
|
|
try {
|
|
return await T[name].apply(null, args)
|
|
} catch (e) {
|
|
throw new Error(`class ${T.name}/ function ${name}/ args ${args.join()}/ ${e.stack}`);
|
|
}
|
|
};
|
|
}
|
|
}
|
|
return T2;
|
|
}
|
|
|
|
export function getModelForClass(T) {
|
|
return getModelForClassPub(catchError(T));
|
|
}
|