12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697 |
- const MongoClient = require("mongodb").MongoClient;
- const ObjectID = require("mongodb").ObjectID;
- const mm = require('mm')
- const {connect} = require('mm')
- module.exports = async (dbName='cb') => {
- const {Savable, slice} = await connect(dbName)
- async function getModels(id){
- const SlicedSavable = slice([id, 'user'])
- class User extends SlicedSavable {
- constructor(...params){
- super(...params)
- this.moneyEvents = this.moneyEvents instanceof Array ? this.moneyEvents : (this.moneyEvents ? [this.moneyEvents] : [])
- }
- static get relations(){
- return {
- moneyEvents: "user"
- }
- }
- }
- SlicedSavable.addClass(User)
- class Event extends SlicedSavable {
- constructor(...params){
- super(...params)
- this.moneyEvents = this.moneyEvents instanceof Array ? this.moneyEvents : (this.moneyEvents ? [this.moneyEvents] : [])
- }
- get owner(){
- return this.___owner
- }
- get usersSum(){
- return (async () => {
- var result = 0;
- for (let money of this.moneyEvents){
- result += (await money).amount
- console.log('MONEY SUM', money.amount, money._id)
- }
- return result;
- })()
- }
- get moneyDiff(){
- return (async () => {
- return (await this.usersSum) - (this.total || 0);
- })()
- }
- get avg(){
- return this.total/((this.moneyEvents && this.moneyEvents.length) || 1)
- }
- static get relations(){
- return {
- moneyEvents: "event"
- }
- }
- }
- SlicedSavable.addClass(Event)
- class EventMoney extends SlicedSavable {
- get owner(){
- return this.___owner
- }
- get avgDiff(){
- return (async () => this.amount - (await this.event).avg)()
- }
- static get relations(){
- return {
- user: "moneyEvents",
- event: "moneyEvents"
- }
- }
- }
- SlicedSavable.addClass(EventMoney)
- const thisUser = await Savable.m.User.findOne({_id: ObjectID(id)})
- return {
- SlicedSavable, User, Event, EventMoney, thisUser
- }
- }
- return {
- Savable,
- slice,
- getModels
- }
- }
|