read.js 895 B

1234567891011121314151617181920212223242526
  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. // 将uri转换成url使用url模块处理
  7. let url = ctx.request.url;
  8. if (!url.includes('http')) {
  9. url = `http://localhost${url}`;
  10. }
  11. const obj = new URL(url);
  12. // 以 / 将字符串分段成为数组
  13. const arr = obj.pathname.split('/');
  14. // fetch的格式是最后的'/'后的内容为ObjectId
  15. const tail = _.last(arr);
  16. // 使用mongoose的 ObjectId类 去校验是否为ObjectId,不是ObjectId的情况,则不能直接使用plus,plus中使用的是findById
  17. const res = ObjectId.isValid(tail);
  18. if (res) {
  19. // service.read.plus对该数据的read+1
  20. await ctx.service.read.plus(options, tail);
  21. }
  22. // 别忘了最后要正常继续工作
  23. await next();
  24. };
  25. };