index.ts 3.3 KB

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