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