category.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. 'use strict';
  2. /**
  3. *
  4. *
  5. * @author Mai
  6. * @date 2018/9/26
  7. * @version
  8. */
  9. const settingConst = require('../const/setting.js');
  10. module.exports = app => {
  11. class Category extends app.BaseService {
  12. /**
  13. * 构造函数
  14. *
  15. * @param {Object} ctx - egg全局变量
  16. * @return {void}
  17. */
  18. constructor(ctx) {
  19. super(ctx);
  20. this.tableName = 'category';
  21. }
  22. async addCategory(pid, name, type) {
  23. const count = await this.count({pid: pid, name: name});
  24. if (count > 0) {
  25. throw '存在同名类别';
  26. }
  27. const category = {
  28. pid: pid,
  29. name: name,
  30. type: type,
  31. };
  32. const result = await this.db.insert(this.tableName, category);
  33. if (result.affectedRows !== 1) {
  34. throw '提交数据失败';
  35. } else {
  36. category.id = result.insertId;
  37. }
  38. category.value = category.value && category.value !== '' ? JSON.parse(category.value) : [];
  39. return category;
  40. }
  41. async getCategory(id) {
  42. const data = await this.getDataByCondition({id: id});
  43. data.value = await this.ctx.service.categoryValue.getAllDataByCondition({ where: {cid: id} });
  44. return data;
  45. }
  46. /**
  47. * 获取标段分类数据
  48. *
  49. * @param {Number} pid - 标段id
  50. * @returns {Promise<*>}
  51. */
  52. async getAllCategory(pid) {
  53. const data = await this.getAllDataByCondition({where: {pid: pid}});
  54. const values = await this.ctx.service.categoryValue.getAllDataByCondition({ where: {pid: pid} });
  55. for (const d of data) {
  56. d.value = values.filter(function (v) {
  57. return v.cid === d.id;
  58. });
  59. }
  60. return data;
  61. }
  62. async resetCategoryLevel(data) {
  63. this.transaction = await this.db.beginTransaction();
  64. try {
  65. for (const d of data) {
  66. this.transaction.update(this.tableName, {id: d.id, level: d.level});
  67. }
  68. this.transaction.commit();
  69. } catch (err) {
  70. await this.transaction.rollback();
  71. throw err;
  72. }
  73. }
  74. }
  75. return Category;
  76. };