logs.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. 'use strict';
  2. const moment = require('moment');
  3. const _ = require('lodash');
  4. const operaMethod = require('../utils/routerword.js');
  5. module.exports = (options, app) => {
  6. return async (ctx, next) => {
  7. try {
  8. const { authorization } = ctx.request.header;
  9. if (authorization) {
  10. let user = decodeURI(authorization);
  11. // console.log(user);
  12. if (user) {
  13. user = JSON.parse(user);
  14. const { path: route, method, query, body, ip } = ctx.request;
  15. if (method !== 'GET') {
  16. const { id, name } = user;
  17. const params = {};
  18. if (query) params.query = query;
  19. if (body) params.body = body;
  20. if (method === 'DELETE') {
  21. const pl = route.split('/');
  22. const last = _.last(pl);
  23. if (last && last.length > 20) {
  24. // >20确保是ObjectId,ObjectId是24位
  25. params.id = last;
  26. }
  27. }
  28. const obj = { route, method, params, userid: id, name, ip };
  29. const opera = operaMethod(route, method);
  30. if (opera) obj.opera = opera;
  31. await ctx.service.logs.create(obj);
  32. }
  33. }
  34. }
  35. } catch (error) {
  36. console.error(`${moment().format('YYYY-MM-DD HH:mm:ss')}日志生成发生错误!`);
  37. console.error(error);
  38. } finally {
  39. await next();
  40. }
  41. };
  42. };