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