'use strict'; const _ = require('lodash'); const { ObjectId } = require('mongoose').Types; module.exports = options => { return async function read(ctx, next) { // 将uri转换成url使用url模块处理 let url = ctx.request.url; if (!url.includes('http')) { url = `http://localhost${url}`; } const obj = new URL(url); // 以 / 将字符串分段成为数组 const arr = obj.pathname.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(); }; };