models.js 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. const ObjectID = require("mongodb").ObjectID;
  2. const {connect} = require('mm')
  3. module.exports = async (dbName='shop') => {
  4. const {Savable, slice} = await connect(dbName)
  5. async function getModels({id}){
  6. const SlicedSavable = slice([id, 'user', 'admin'])
  7. class User extends SlicedSavable {
  8. constructor(...params){
  9. super(...params)
  10. this.orders = this.orders instanceof Array ? this.orders : (this.orders ? [this.orders] : [])
  11. }
  12. static get relations(){
  13. return {
  14. orders: "user"
  15. }
  16. }
  17. }
  18. SlicedSavable.addClass(User)
  19. class Good extends SlicedSavable {
  20. constructor(...params){
  21. super(...params)
  22. this.categories = this.categories instanceof Array ? this.categories : (this.categories ? [this.categories] : [])
  23. this.orderGoods = this.orderGoods instanceof Array ? this.orderGoods : (this.orderGoods ? [this.orderGoods] : [])
  24. }
  25. static get relations(){
  26. return {
  27. categories: ["goods"],
  28. orderGoods: "good",
  29. }
  30. }
  31. }
  32. SlicedSavable.addClass(Good)
  33. class Category extends SlicedSavable {
  34. constructor(...params){
  35. super(...params)
  36. this.goods = this.goods instanceof Array ? this.goods : (this.goods ? [this.goods] : [])
  37. }
  38. static get relations(){
  39. return {
  40. goods: ["categories"],
  41. }
  42. }
  43. }
  44. SlicedSavable.addClass(Category)
  45. class Order extends SlicedSavable {
  46. constructor(...params){
  47. super(...params)
  48. this.orderGoods = Savable.arrize(this.orderGoods)
  49. }
  50. get total(){
  51. return (async() => (await Promise.all(this.orderGoods)).reduce((a,b) => (a.total || a) + b.total, 0))()
  52. }
  53. static get relations(){
  54. return {
  55. user: ["orders"],
  56. orderGoods: "order"
  57. }
  58. }
  59. }
  60. SlicedSavable.addClass(Order)
  61. class OrderGood extends SlicedSavable {
  62. constructor(...params){
  63. super(...params)
  64. }
  65. get total(){
  66. return this.price*this.count
  67. }
  68. static get relations(){
  69. return {
  70. good: ["orderGoods"],
  71. order: ["orderGoods"]
  72. }
  73. }
  74. }
  75. SlicedSavable.addClass(OrderGood)
  76. const thisUser = await Savable.m.User.findOne({_id: ObjectID(id)})
  77. return {models: {
  78. SlicedSavable, User, Good, Category, Order, OrderGood
  79. },
  80. thisUser}
  81. }
  82. return {
  83. Savable,
  84. slice,
  85. getModels
  86. }
  87. }