base_service.js 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  1. 'use strict';
  2. /**
  3. * 业务逻辑基类
  4. *
  5. * @author Mai
  6. * @date 2018/4/19
  7. * @version
  8. */
  9. const Service = require('egg').Service;
  10. class BaseService extends Service {
  11. /**
  12. * 构造函数
  13. *
  14. * @param {Object} ctx - egg全局context
  15. * @return {void}
  16. */
  17. constructor(ctx) {
  18. super(ctx);
  19. this.db = this.app.mysql;
  20. }
  21. /**
  22. * 设置表名
  23. *
  24. * @param {String} table - 表名
  25. * @return {void}
  26. */
  27. set tableName(table) {
  28. this._table = this.app.config.tablePrefix + table;
  29. }
  30. /**
  31. * 获取表名
  32. *
  33. * @return {String} - 返回表名
  34. */
  35. get tableName() {
  36. return this._table;
  37. }
  38. /**
  39. * 根据id查找数据
  40. *
  41. * @param {Number} id - 数据库中的id
  42. * @return {Object} - 返回单条数据
  43. */
  44. async getDataById(id) {
  45. return await this.db.get(this.tableName, { id });
  46. }
  47. /**
  48. * 根据条件查找单条数据
  49. *
  50. * @param {Object} condition - 筛选条件
  51. * @return {Object} - 返回单条数据
  52. */
  53. async getDataByCondition(condition) {
  54. return await this.db.get(this.tableName, condition);
  55. }
  56. /**
  57. * 根据条件查找数据
  58. *
  59. * @param {Object} condition - 筛选条件
  60. * @return {Array} - 返回数据
  61. */
  62. async getAllDataByCondition(condition) {
  63. return await this.db.select(this.tableName, condition);
  64. }
  65. /**
  66. * 根据id删除数据
  67. *
  68. * @param {Number} id - 数据库中的id
  69. * @return {boolean} - 返回是否删除成功
  70. */
  71. async deleteById(id) {
  72. const result = await this.db.delete(this.tableName, { id });
  73. return result.affectedRows > 0;
  74. }
  75. /**
  76. * 获取总数
  77. *
  78. * @param {Object} option - 过滤条件(参考select方法中的condition)
  79. * @return {Number} - 返回查找的总数
  80. */
  81. async count(option = {}) {
  82. const result = await this.db.count(this.tableName, option);
  83. return result;
  84. }
  85. /**
  86. * 获取分页数据
  87. *
  88. * @param {Object} condition - 搜索条件
  89. * @return {Array} - 返回分页数据
  90. */
  91. async getList(condition) {
  92. const page = this.ctx.page;
  93. // 分页设置
  94. condition.limit = condition.limit === undefined ? this.app.config.pageSize : condition.limit;
  95. condition.offset = condition.offset === undefined ? this.app.config.pageSize * (page - 1) : condition.offset;
  96. if (this.ctx.sort !== undefined && this.ctx.sort.length > 0) {
  97. condition.orders = [this.ctx.sort];
  98. }
  99. const list = await this.db.select(this.tableName, condition);
  100. return list;
  101. }
  102. }
  103. module.exports = BaseService;