baseService.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. 'use strict';
  2. const Service = require('egg').Service;
  3. class BaseService extends Service {
  4. async one(id, pop) {
  5. return pop ? await this.tag().findById(id).populate(pop)
  6. : await this.tag().findById(id);
  7. }
  8. async oneData(data, pop) {
  9. const sort = data.sort;
  10. delete data.sort;
  11. if (pop) {
  12. return sort ? await this.tag().findOne(data).populate(pop)
  13. .sort(sort)
  14. : await this.tag().findOne(data).populate(pop);
  15. }
  16. return sort ? await this.tag().findOne(data).sort(sort)
  17. : await this.tag().findOne(data);
  18. }
  19. async list(data, pop) {
  20. const sort = data.sort;
  21. delete data.sort;
  22. if (pop) {
  23. return sort ? await this.tag().find(data).populate(pop)
  24. .sort(sort)
  25. : await this.tag().find(data).populate(pop);
  26. }
  27. return sort ? await this.tag().find(data).sort(sort)
  28. : await this.tag().find(data);
  29. }
  30. async listForPage(data, pop) {
  31. const page = data.page || 1;
  32. const rows = Number.parseInt(data.rows)
  33. || this.app.config.defaultPageSize;
  34. const sort = data.sort;
  35. delete data.page;
  36. delete data.rows;
  37. delete data.sort;
  38. if (pop) {
  39. const total = await this.tag().find(data).countDocuments();
  40. const result = (sort ? await this.tag().find(data).populate(pop)
  41. .sort(sort)
  42. .skip((page - 1) * rows)
  43. .limit(rows)
  44. : await this.tag().find(data).populate(pop)
  45. .skip((page - 1) * rows)
  46. .limit(rows));
  47. return {
  48. count: total,
  49. list: result,
  50. };
  51. }
  52. const total = await this.tag().find(data).countDocuments();
  53. const result = (sort ? await this.tag().find(data).sort(sort)
  54. .skip((page - 1) * rows)
  55. .limit(rows)
  56. : await this.tag().find(data).skip((page - 1) * rows)
  57. .limit(rows));
  58. return {
  59. count: total,
  60. list: result,
  61. };
  62. }
  63. async add(data) {
  64. return await this.tag().create(data);
  65. }
  66. async update(id, data) {
  67. return await this.tag().updateOne({ _id: id }, data);
  68. }
  69. async updateAll(cond, data) {
  70. return await this.tag().update(cond, data);
  71. }
  72. async delete(id) {
  73. return await this.tag().deleteOne({ _id: id });
  74. }
  75. async deleteAll(cond) {
  76. return await this.tag().delete(cond);
  77. }
  78. }
  79. module.exports = BaseService;