read.js 751 B

12345678910111213141516171819202122
  1. 'use strict';
  2. const _ = require('lodash');
  3. const { ObjectId } = require('mongoose').Types;
  4. module.exports = options => {
  5. return async function read(ctx, next) {
  6. // 获取url
  7. const uri = ctx.request.url;
  8. // 以 / 将字符串分段成为数组
  9. const arr = uri.split('/');
  10. // fetch的格式是最后的'/'后的内容为ObjectId
  11. const tail = _.last(arr);
  12. // 使用mongoose的 ObjectId类 去校验是否为ObjectId,不是ObjectId的情况,则不能直接使用plus,plus中使用的是findById
  13. const res = ObjectId.isValid(tail);
  14. if (res) {
  15. // service.read.plus对该数据的read+1
  16. await ctx.service.read.plus(options, tail);
  17. }
  18. // 别忘了最后要正常继续工作
  19. await next();
  20. };
  21. };