mock平台

storage.js 1.2KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. const baseModel = require('./base.js');
  2. const mongoose = require('mongoose');
  3. class stroageModel extends baseModel {
  4. constructor() {
  5. super()
  6. let storageCol = mongoose.connection.db.collection('storage');
  7. storageCol.createIndex(
  8. {
  9. key: 1
  10. },
  11. {
  12. unique: true
  13. }
  14. );
  15. }
  16. getName() {
  17. return 'storage';
  18. }
  19. getSchema() {
  20. return {
  21. key: { type: Number, required: true },
  22. data: {
  23. type: String,
  24. default: ''
  25. } //用于原始数据存储
  26. };
  27. }
  28. save(key, data = {}, isInsert = false) {
  29. let saveData = {
  30. key,
  31. data: JSON.stringify(data, null, 2)
  32. };
  33. if(isInsert){
  34. let r = new this.model(saveData);
  35. return r.save();
  36. }
  37. return this.model.updateOne({
  38. key
  39. }, saveData)
  40. }
  41. del(key) {
  42. return this.model.remove({
  43. key
  44. });
  45. }
  46. get(key) {
  47. return this.model
  48. .findOne({
  49. key
  50. })
  51. .exec().then(data => {
  52. this.save(key, {})
  53. if (!data) return null;
  54. data = data.toObject().data;
  55. try {
  56. return JSON.parse(data)
  57. } catch (e) {
  58. return {}
  59. }
  60. });
  61. }
  62. }
  63. module.exports = stroageModel;