read.js 803 B

1234567891011121314151617181920212223
  1. 'use strict';
  2. const { CrudService } = require('naf-framework-mongoose/lib/service');
  3. const { BusinessError, ErrorCode } = require('naf-core').Error;
  4. const _ = require('lodash');
  5. const assert = require('assert');
  6. // 阅读数加一
  7. class ReadService extends CrudService {
  8. constructor(ctx) {
  9. super(ctx, 'read');
  10. }
  11. async plus(model, id) {
  12. assert(model && id, '缺少数据');
  13. // _.capitalize=>首字母大写
  14. const data = await this.ctx.model[_.capitalize(model)].findById(id);
  15. if (!data) throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '未找到要阅读的数据');
  16. // 默认将read给0,别引起错误,数据不对可以讨论,找原因,但是程序中断了就不好了
  17. data.read = (data.read || 0) + 1;
  18. await data.save();
  19. }
  20. }
  21. module.exports = ReadService;