lrf402788946 il y a 4 ans
Parent
commit
1f8c2a0672
1 fichiers modifiés avec 55 ajouts et 0 suppressions
  1. 55 0
      app/service/util/spm.js

+ 55 - 0
app/service/util/spm.js

@@ -55,6 +55,61 @@ class SpmService extends CrudService {
     }
     return res;
   }
+
+  /**
+   * 直接操作model做什么
+   * @param {Object} condition 条件
+   * @property {String} model 表
+   * @property {String} method mongoose的函数
+   * @property {Object} query 查询条件
+   * @property {Object} body 添加/修改数据
+   * @property {String/Object} projection 查询使用,选取指定字段
+   */
+  async useModel(condition = {}) {
+    const { method, query = {}, body = {}, projection } = condition;
+    let { model } = condition;
+    model = _.capitalize(model);
+    assert(model, '缺少指定表');
+    assert(method, '缺少使用函数');
+    // 区分method的情况
+    let res;
+    // 添加/批量添加
+    if (method === 'create' || method === 'insertMany') {
+      res = await this.ctx.model[model][method](body);
+    }
+    // 修改(updateOne)/批量修改(updateMany)
+    if (method.includes('update')) {
+      res = await this.ctx.model[model][method](query, body);
+    }
+    // 删除(deleteOne)/批量删除(deleteMany)
+    if (method.includes('delete')) {
+      res = await this.ctx.model[model][method](query);
+    }
+    // 查询(find,findById,findOne),反正都是只要query
+    if (method.includes('find')) {
+      res = await this.ctx.model[model][method](query, projection);
+    }
+    // 再下来,就是聚合了,聚合就算了吧.这个还跨项目写就没啥必要了
+    return res;
+  }
+
+  /**
+   * 调用service
+   * @param {Object} condition 条件
+   * @property {String} model 表
+   * @property {String} method mongoose的函数
+   */
+  async useService(condition) {
+    const { service, method, body } = condition;
+    assert(service, '缺少指定表');
+    assert(method, '缺少使用函数');
+    const arr = service.split('.');
+    let serve = this.ctx.service;
+    for (const i of arr) {
+      serve = serve[i];
+    }
+    return await serve[method](body);
+  }
 }
 
 module.exports = SpmService;