|
@@ -17,9 +17,15 @@ class GoodsService extends CrudService {
|
|
|
async beforeCreate(data) {
|
|
|
// 为商品随机生成不重复的code
|
|
|
if (!data.code) data.code = await this.makeCode();
|
|
|
+ await this.checkCode(data.code);
|
|
|
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) {
|
|
@@ -29,6 +35,19 @@ class GoodsService extends CrudService {
|
|
|
}
|
|
|
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() {
|