import mongooseUniqueValidator from "mongoose-unique-validator"; import {AppMaster} from "@onebro/appmaster"; import { DeepPartial, IModelCreator, IStatus, IQuery, mapSelectedData, getSchemaRefs, ObjectId} from "@onebro/oba-common"; import { FinavigatorMessageConfig, FinavigatorMessageModel, FinavigatorMessage, FinavigatorMessageJson, FinavigatorMessageStatuses as statuses, FinavigatorMessageStatus,} from "../types"; import {finavigatorMessageSchema as msg} from "../schemas"; const refs = getSchemaRefs(msg); export const finavigatorMessageModels:IModelCreator = async m => { msg.plugin(mongooseUniqueValidator); msg.virtual("lastStatus").get(function(){return this.status?(this.status[this.status.length - 1] as any).json(statuses):null;}); msg.virtual("lastStatus").set(function(o:IStatus){this.status = [...this.status,o];}); msg.virtual("statusStr").get(function(){return this.lastStatus?this.lastStatus.name + " @ " + this.lastStatus.time:"";}); msg.statics._populate = async function(o?:FinavigatorMessage){ await o.populate(refs).execPopulate(); return o;}; msg.statics._find = async function(o:Partial|string){ if(!o) return m.e.badinfo(); const p = typeof o == "string"? await FinavigatorMessage.findById(o): await FinavigatorMessage.findOne(FinavigatorMessage.translateAliases(o)); if(!p) throw m.e.doesNotExist("message"); return p;}; msg.statics._create = async function(o:FinavigatorMessageConfig){return new FinavigatorMessage({ ...o, author:new ObjectId(o.author), });}; msg.statics._update = async function(o:FinavigatorMessage,p:DeepPartial){ await o.set(p).save(); return await FinavigatorMessage._populate(o);}; msg.statics._remove = async function(o:FinavigatorMessage){return await o.remove().then(() => ({removed:o._id}));}; msg.statics._query = async function(o:IQuery){ const {query,populate,limit,skip,sort,select} = o; const results:FinavigatorMessage[] = await this.find(this.translateAliases(query)) .populate(populate) //.where(where) .limit(limit) .skip(skip) .sort(sort) .exec(); const msgs = mapSelectedData(select,results); return {msgs};}; msg.statics._lookup = async function({path,query}:{path:string;query:any}){ const pipeline:any[] = []; return FinavigatorMessage.aggregate(pipeline) .exec() .then((R:Partial<{[k in keyof (FinavigatorMessage & FinavigatorMessageJson)]:any}>[]) => { return {msgs:R.map(o => { if(o.status) o.status = { name:statuses[o.status.a0 as FinavigatorMessageStatus], time:o.status.a1, until:o.status.a2, info:o.status.a3}; delete o._id; return o;})}; });}; msg.methods.json = function(){ const {id,created,updated,lastStatus:status,statusStr,type,author,body} = this as FinavigatorMessage; const json:FinavigatorMessageJson = { id,created,updated,status,statusStr, type,author:author.preview(), body,published:new Date(created), }; return json;}; const FinavigatorMessage = m.db.model("onebrother","FinavigatorMessage",msg); await FinavigatorMessage.init(); return {FinavigatorMessage}; };