proxy.service.ts 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. import { Config, Inject, InjectClient, Provide } from '@midwayjs/core';
  2. import { Context } from '@midwayjs/koa';
  3. import { RequestBase } from '../interface/proxy.interface';
  4. import { get, lowerCase, pick } from 'lodash';
  5. import { HttpServiceFactory, HttpService } from '@midwayjs/axios';
  6. import { Axios } from '@midwayjs/axios';
  7. @Provide()
  8. export class ProxyService {
  9. @Inject()
  10. ctx: Context;
  11. @Config('axios.clients')
  12. axiosClients: object;
  13. @InjectClient(HttpServiceFactory, 'default')
  14. serviceAxios: HttpService;
  15. @Inject()
  16. sf: HttpServiceFactory;
  17. getRequstBase(): RequestBase {
  18. const request = this.ctx.request;
  19. const result: RequestBase = pick(request, [
  20. 'method',
  21. 'header',
  22. 'path',
  23. 'query',
  24. 'querystring',
  25. 'body',
  26. 'rawBody',
  27. 'host',
  28. 'ip',
  29. 'originalUrl',
  30. ]) as RequestBase;
  31. return result;
  32. }
  33. async toProxy() {
  34. const rb: RequestBase = this.getRequstBase();
  35. // 解析路由前缀
  36. const uri = rb.originalUrl;
  37. const keys = Object.keys(this.axiosClients);
  38. let url;
  39. for (const prefix of keys) {
  40. const regRules = `^(${prefix})`;
  41. const reg = new RegExp(regRules);
  42. const res = reg.test(uri);
  43. if (!res) continue;
  44. const clientConfig = this.axiosClients[prefix];
  45. const baseURL = clientConfig.baseURL;
  46. // 去掉前缀
  47. // url = uri.replace(reg, baseURL);
  48. // 保留前缀(目前采用这一方式处理)
  49. url = `${baseURL}${rb.originalUrl}`;
  50. break;
  51. }
  52. if (!url) return;
  53. console.log(url);
  54. const reqConfig: any = {
  55. url,
  56. method: rb.method,
  57. headers: rb.header,
  58. };
  59. if (lowerCase(rb.method) === 'post') reqConfig.data = rb.body;
  60. const res = await this.serviceAxios.request(reqConfig);
  61. if (res.status !== 200) throw new Error('proxy service request error');
  62. return res.data;
  63. }
  64. async getAxios(clientConfig: object): Promise<Axios.AxiosInstance> {
  65. const rb: RequestBase = this.getRequstBase();
  66. const axi = await this.sf.createInstance({
  67. ...clientConfig,
  68. header: get(rb, 'header'),
  69. });
  70. return axi;
  71. }
  72. }