index.ts 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  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. console.log('------ Request headers -------', req.headers);
  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. if (milvusAddress && insightCache.has(milvusAddress)) {
  21. MilvusService.activeAddress = milvusAddress;
  22. // insight cache will update expire time when use insightCache.get
  23. MilvusService.activeMilvusClient = insightCache.get(
  24. MilvusService.formatAddress(milvusAddress)
  25. );
  26. }
  27. next();
  28. };
  29. export const TransformResMiddlerware = (
  30. req: Request,
  31. res: Response,
  32. next: NextFunction
  33. ) => {
  34. const oldSend = res.json;
  35. res.json = data => {
  36. // console.log(data); // do something with the data
  37. const statusCode = data?.statusCode;
  38. const message = data?.message;
  39. const error = data?.error;
  40. res.json = oldSend; // set function back to avoid the 'double-send'
  41. if (statusCode || message || error) {
  42. return res.json({ statusCode, message, error });
  43. }
  44. return res.json({ data, statusCode: 200 }); // just call as normal with data
  45. };
  46. next();
  47. };
  48. /**
  49. * Handle error in here.
  50. * Normally depend on status which from milvus service.
  51. */
  52. export const ErrorMiddleware = (
  53. err: HttpError,
  54. req: Request,
  55. res: Response,
  56. next: NextFunction
  57. ) => {
  58. const statusCode = err.statusCode || 500;
  59. console.log(
  60. chalk.blue.bold(req.method, req.url),
  61. chalk.magenta.bold(statusCode),
  62. chalk.red.bold(err)
  63. );
  64. // Boolean property that indicates if the app sent HTTP headers for the response.
  65. // Here to prevent sending response after header has been sent.
  66. if (res.headersSent) {
  67. return next(err);
  68. }
  69. if (err) {
  70. res
  71. .status(statusCode)
  72. .json({ message: `${err}`, error: 'Bad Request', statusCode });
  73. }
  74. next();
  75. };
  76. export const LoggingMiddleware = morgan((tokens, req, res) => {
  77. return [
  78. '\n',
  79. chalk.blue.bold(tokens.method(req, res)),
  80. chalk.magenta.bold(tokens.status(req, res)),
  81. chalk.green.bold(tokens.url(req, res)),
  82. chalk.green.bold(tokens['response-time'](req, res) + ' ms'),
  83. chalk.green.bold('@ ' + tokens.date(req, res)),
  84. chalk.yellow(tokens['remote-addr'](req, res)),
  85. chalk.hex('#fffa65').bold('from ' + tokens.referrer(req, res)),
  86. chalk.hex('#1e90ff')(tokens['user-agent'](req, res)),
  87. '\n',
  88. ].join(' ');
  89. });