api.js 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. 'use strict';
  2. const assert = require('assert');
  3. const { CrudService } = require('naf-framework-mongoose/lib/service');
  4. const { isNullOrUndefined, trimData } = require('naf-core').Util;
  5. const { BusinessError, ErrorCode } = require('naf-core').Error;
  6. const _ = require('lodash');
  7. class ApiService extends CrudService {
  8. constructor(ctx) {
  9. super(ctx, 'naf_code_items');
  10. this.mItems = this.ctx.model.Items;
  11. this.mCategory = this.ctx.model.Category;
  12. this.model = this.mItems;
  13. }
  14. async list({ category, group } = {}) {
  15. assert(category, '类别不能为空');
  16. // const rs = await this.model.find(trimData(data), null, trimData({ skip, limit, sort: order && { [order]: 1 } })).exec();
  17. const c = await this.mCategory.findOne({ $or: [{ code: category }, { key: category }] }).exec();
  18. if (isNullOrUndefined(c)) {
  19. throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '字典类别不存在');
  20. }
  21. const rs = await this.mItems.find(trimData({ category: c.code, group }), { code: 1, name: 1, _id: -1 }, { sort: { order: -1, code: 1 } }).exec();
  22. return rs.map(p => ({ code: p.code, name: p.name }));
  23. }
  24. async xzqh({ parent, level } = {}) {
  25. assert(isNullOrUndefined(parent) || /^\d{6}$/.test(parent), 'parent必须为有效的行政区划代码');
  26. assert(level, 'level不能为空');
  27. if (!_.isNumber(level)) level = Number(level);
  28. assert(level >= 0 && level <= 3, 'level只能为0~3的数字');
  29. const filter = { category: '31' };
  30. if (level > 0) {
  31. const suffix = '000000'.substr(0, (3 - level) * 2);
  32. let prefix = '';
  33. if (!isNullOrUndefined(parent) && level > 1) prefix = parent.substr(0, (level - 1) * 2);
  34. filter.code = { $regex: `${prefix}\\d{2}(?<!00)${suffix}` };
  35. }
  36. const rs = await this.mItems.find(filter, { code: 1, name: 1, _id: -1 }, { sort: { order: -1, code: 1 } }).exec();
  37. return rs.map(p => ({ code: p.code, name: p.name }));
  38. }
  39. async fetch({ category, group, code } = {}) {
  40. assert(category, 'category不能为空');
  41. assert(code, 'code不能为空');
  42. // const rs = await this.model.find(trimData(data), null, trimData({ skip, limit, sort: order && { [order]: 1 } })).exec();
  43. const c = await this.mCategory.findOne({ $or: [{ code: category }, { key: category }] }).exec();
  44. if (isNullOrUndefined(c)) {
  45. throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '字典类别不存在');
  46. }
  47. const rs = await this.mItems.findOne({ category: c.code, group, code }, { code: 1, name: 1, _id: -1 }).exec();
  48. return rs;
  49. }
  50. }
  51. module.exports = ApiService;