models.js 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  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. static get relations(){
  52. return {
  53. user: "orders",
  54. orderGoods: "order"
  55. }
  56. }
  57. }
  58. SlicedSavable.addClass(Order)
  59. class OrderGood extends SlicedSavable {
  60. constructor(...params){
  61. super(...params)
  62. }
  63. static get relations(){
  64. return {
  65. good: "orderGoods",
  66. order: "orderGoods"
  67. }
  68. }
  69. }
  70. SlicedSavable.addClass(OrderGood)
  71. const thisUser = await Savable.m.User.findOne({_id: ObjectID(id)})
  72. return {
  73. SlicedSavable, User, Good, Category, Order, OrderGood
  74. }
  75. }
  76. return {
  77. Savable,
  78. slice,
  79. getModels
  80. }
  81. }