models.js 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. const MongoClient = require("mongodb").MongoClient;
  2. const ObjectID = require("mongodb").ObjectID;
  3. const mm = require('mm')
  4. const {connect} = require('mm')
  5. module.exports = async (dbName='cb') => {
  6. const {Savable, slice} = await connect(dbName)
  7. async function getModels(id){
  8. const SlicedSavable = slice([id, 'user'])
  9. class User extends SlicedSavable {
  10. constructor(...params){
  11. super(...params)
  12. this.moneyEvents = this.moneyEvents instanceof Array ? this.moneyEvents : (this.moneyEvents ? [this.moneyEvents] : [])
  13. }
  14. static get relations(){
  15. return {
  16. moneyEvents: "user"
  17. }
  18. }
  19. }
  20. SlicedSavable.addClass(User)
  21. class Event extends SlicedSavable {
  22. constructor(...params){
  23. super(...params)
  24. this.moneyEvents = this.moneyEvents instanceof Array ? this.moneyEvents : (this.moneyEvents ? [this.moneyEvents] : [])
  25. }
  26. get owner(){
  27. return this.___owner
  28. }
  29. get usersSum(){
  30. return (async () => {
  31. var result = 0;
  32. for (let money of this.moneyEvents){
  33. result += (await money).amount
  34. console.log('MONEY SUM', money.amount, money._id)
  35. }
  36. return result;
  37. })()
  38. }
  39. get moneyDiff(){
  40. return (async () => {
  41. return (await this.usersSum) - (this.total || 0);
  42. })()
  43. }
  44. get avg(){
  45. return this.total/((this.moneyEvents && this.moneyEvents.length) || 1)
  46. }
  47. static get relations(){
  48. return {
  49. moneyEvents: "event"
  50. }
  51. }
  52. }
  53. SlicedSavable.addClass(Event)
  54. class EventMoney extends SlicedSavable {
  55. get owner(){
  56. return this.___owner
  57. }
  58. get avgDiff(){
  59. return (async () => this.amount - (await this.event).avg)()
  60. }
  61. static get relations(){
  62. return {
  63. user: "moneyEvents",
  64. event: "moneyEvents"
  65. }
  66. }
  67. }
  68. SlicedSavable.addClass(EventMoney)
  69. const thisUser = await Savable.m.User.findOne({_id: ObjectID(id)})
  70. return {
  71. SlicedSavable, User, Event, EventMoney, thisUser
  72. }
  73. }
  74. return {
  75. Savable,
  76. slice,
  77. getModels
  78. }
  79. }