banner.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. 'use strict';
  2. const Service = require('egg').Service;
  3. const assert = require('assert');
  4. const moment = require('moment');
  5. class ContentService extends Service {
  6. async create({ title, shortTitle, slug, path, annex, content, annexname }) {
  7. assert(title, '标题不存在');
  8. assert(shortTitle, '短标题不存在');
  9. assert(slug, '摘要不存在');
  10. assert(path, '轮播图不存在');
  11. assert(content, '内容不存在');
  12. const { Banner: model } = this.ctx.model;
  13. const createAt = moment().format('x');
  14. try {
  15. await model.create({ title, shortTitle, slug, path, annex, content, createAt, annexname });
  16. return { errmsg: '', errcode: 0 };
  17. } catch (error) {
  18. console.log(error);
  19. throw new Error({ errcode: -2001, errmsg: '添加失败' });
  20. }
  21. }
  22. async update({ title, shortTitle, slug, path, annex, content, istop, _id, annexname }) {
  23. assert(_id, 'id不存在');
  24. const { Banner: model } = this.ctx.model;
  25. try {
  26. await model.findById(_id).update({ title, shortTitle, slug, path, annex, content, istop, annexname });
  27. return { errmsg: '', errcode: 0 };
  28. } catch (error) {
  29. throw new Error({ errcode: -2001, errmsg: '修改失败' });
  30. }
  31. }
  32. async del({ id }) {
  33. assert(id, 'id不存在');
  34. const { Banner: model } = this.ctx.model;
  35. try {
  36. await model.findById(id).remove();
  37. return { errmsg: '', errcode: 0 };
  38. } catch (error) {
  39. throw new Error({ errcode: -2001, errmsg: '删除失败' });
  40. }
  41. }
  42. async details({ id }) {
  43. assert(id, 'id不存在');
  44. const { Banner: model } = this.ctx.model;
  45. try {
  46. const res = await model.findById(id);
  47. return { errmsg: '', errcode: 0, data: res };
  48. } catch (error) {
  49. throw new Error({ errcode: -2001, errmsg: '查询失败' });
  50. }
  51. }
  52. async query({ skip, limit, title }) {
  53. const { Banner: model } = this.ctx.model;
  54. const filter = {};
  55. if (title) filter.title = title;
  56. const total = await model.find();
  57. try {
  58. let res;
  59. if (skip && limit) {
  60. res = await model.find({ ...filter }, { content: false }).skip(Number(skip) * Number(limit)).limit(Number(limit));
  61. } else {
  62. res = await model.find({ ...filter }, { content: false });
  63. }
  64. return { errmsg: '', errcode: 0, data: res, total: total.length };
  65. } catch (error) {
  66. throw new Error({ errcode: -2001, errmsg: '查询失败' });
  67. }
  68. }
  69. }
  70. module.exports = ContentService;