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