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