Browse Source

检测商品code是否重复

lrf 2 years ago
parent
commit
8d55881a61
1 changed files with 20 additions and 1 deletions
  1. 20 1
      app/service/shop/goods.js

+ 20 - 1
app/service/shop/goods.js

@@ -17,9 +17,15 @@ class GoodsService extends CrudService {
   async beforeCreate(data) {
   async beforeCreate(data) {
     // 为商品随机生成不重复的code
     // 为商品随机生成不重复的code
     if (!data.code) data.code = await this.makeCode();
     if (!data.code) data.code = await this.makeCode();
+    await this.checkCode(data.code);
     return data;
     return data;
   }
   }
-
+  async beforeUpdate(filter, update) {
+    const id = _.get(filter, 'id', _.get(filter, '_id'));
+    const code = _.get(update, 'code');
+    await this.checkCode(code, id);
+    return { filter, update };
+  }
 
 
   // 标签查询
   // 标签查询
   async beforeQuery(filter) {
   async beforeQuery(filter) {
@@ -29,6 +35,19 @@ class GoodsService extends CrudService {
     }
     }
     return filter;
     return filter;
   }
   }
+  /**
+   * 检查商品编码是否唯一,若传id,则将该id排除在外
+   * @param {String} code 商品唯一编码
+   * @param {String} id 商品id
+   */
+  async checkCode(code, id) {
+    if (!code) return;
+    const query = { code };
+    if (id) query.id = { $ne: id };
+    const num = await this.model.find(query);
+    if (num > 0) throw new BusinessError(ErrorCode.DATA_EXISTED, '该编码已被其他商品使用');
+    return;
+  }
 
 
   // 生成商品编码
   // 生成商品编码
   async makeCode() {
   async makeCode() {