models.js 3.0 KB

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