index.ts 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. import { Request, Response, NextFunction, Errback } from 'express';
  2. import morgan from 'morgan';
  3. import chalk from 'chalk';
  4. import { MilvusService } from '../milvus/milvus.service';
  5. import { INSIGHT_CACHE, MILVUS_ADDRESS } from '../utils/Const';
  6. import { HttpError } from 'http-errors';
  7. export const ReqHeaderMiddleware = (
  8. req: Request,
  9. res: Response,
  10. next: NextFunction
  11. ) => {
  12. const insightCache = req.app.get(INSIGHT_CACHE);
  13. // all ape requests need set milvus address in header.
  14. // server will set activeaddress in milvus service.
  15. const milvusAddress = (req.headers[MILVUS_ADDRESS] as string) || '';
  16. /**
  17. * only api request has MILVUS_ADDRESS.
  18. * When client run in express, we dont need static files like: xx.js run this logic.
  19. * Otherwise will cause 401 error.
  20. * */
  21. if (milvusAddress && insightCache.has(milvusAddress)) {
  22. MilvusService.activeAddress = milvusAddress;
  23. // insight cache will update expire time when use insightCache.get
  24. MilvusService.activeMilvusClient = insightCache.get(
  25. MilvusService.formatAddress(milvusAddress)
  26. );
  27. }
  28. next();
  29. };
  30. export const TransformResMiddlerware = (
  31. req: Request,
  32. res: Response,
  33. next: NextFunction
  34. ) => {
  35. const oldSend = res.json;
  36. res.json = data => {
  37. // console.log(data); // do something with the data
  38. const statusCode = data?.statusCode;
  39. const message = data?.message;
  40. const error = data?.error;
  41. res.json = oldSend; // set function back to avoid the 'double-send'
  42. if (statusCode || message || error) {
  43. return res.json({ statusCode, message, error });
  44. }
  45. return res.json({ data, statusCode: 200 }); // just call as normal with data
  46. };
  47. next();
  48. };
  49. /**
  50. * Handle error in here.
  51. * Normally depend on status which from milvus service.
  52. */
  53. export const ErrorMiddleware = (
  54. err: HttpError,
  55. req: Request,
  56. res: Response,
  57. next: NextFunction
  58. ) => {
  59. const statusCode = err.statusCode || 500;
  60. console.log(
  61. chalk.blue.bold(req.method, req.url),
  62. chalk.magenta.bold(statusCode),
  63. chalk.red.bold(err)
  64. );
  65. // Boolean property that indicates if the app sent HTTP headers for the response.
  66. // Here to prevent sending response after header has been sent.
  67. if (res.headersSent) {
  68. return next(err);
  69. }
  70. if (err) {
  71. res
  72. .status(statusCode)
  73. .json({ message: `${err}`, error: 'Bad Request', statusCode });
  74. }
  75. next();
  76. };
  77. export const LoggingMiddleware = morgan((tokens, req, res) => {
  78. return [
  79. '\n',
  80. chalk.blue.bold(tokens.method(req, res)),
  81. chalk.magenta.bold(tokens.status(req, res)),
  82. chalk.green.bold(tokens.url(req, res)),
  83. chalk.green.bold(tokens['response-time'](req, res) + ' ms'),
  84. chalk.green.bold('@ ' + tokens.date(req, res)),
  85. chalk.yellow(tokens['remote-addr'](req, res)),
  86. chalk.hex('#fffa65').bold('from ' + tokens.referrer(req, res)),
  87. chalk.hex('#1e90ff')(tokens['user-agent'](req, res)),
  88. '\n',
  89. ].join(' ');
  90. });