import mongooseUniqueValidator from "mongoose-unique-validator"; import {AppMaster} from "@onebro/appmaster"; import { DeepPartial, IModelCreator, IStatus, IQuery, mapSelectedData, getSchemaRefs, ObjectId} from "@onebro/oba-common"; import { SageListMessageConfig, SageListMessageModel, SageListMessage, SageListMessageJson, SageListMessageStatuses as statuses, SageListMessageStatus,} from "../types"; import {sageListMessageSchema as msg} from "../schemas"; const refs = getSchemaRefs(msg); export const sageListMessageModels: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?:SageListMessage){ 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 SageListMessage.findById(o): await SageListMessage.findOne(SageListMessage.translateAliases(o)); if(!p) throw m.e.doesNotExist("message"); return p;}; msg.statics._create = async function(o:SageListMessageConfig){return new SageListMessage({ ...o, author:new ObjectId(o.author), });}; msg.statics._update = async function(o:SageListMessage,p:DeepPartial){ await o.set(p).save(); return await SageListMessage._populate(o);}; msg.statics._remove = async function(o:SageListMessage){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:SageListMessage[] = 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 SageListMessage.aggregate(pipeline) .exec() .then((R:Partial<{[k in keyof (SageListMessage & SageListMessageJson)]:any}>[]) => { return {msgs:R.map(o => { if(o.status) o.status = { name:statuses[o.status.a0 as SageListMessageStatus], 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,img,link,symbol,sendAt,subscribers} = this as SageListMessage; const json:SageListMessageJson = { id,created,updated,status,statusStr, type,author:author.preview(), body,img,link,symbol,sendAt, published:new Date(created), subscribers}; return json;}; const SageListMessage = m.db.model("onebrother","SageListMessage",msg); await SageListMessage.init(); return {SageListMessage}; };