我们提供了一个 HTTP 客户端 RestOperations,该实现是前后端通用的, RestOperations 接口本质是继承了 axios ,接口方法签名是一样的。

使用方式

使用 @Autowired(RestOperations) 注入 HTTP 客户端服务对象到你的业务对象中。示例代码如下:

  1. import { JWKS } from 'jose';
  2. import { JwkSetManager } from './jwk-protocol';
  3. import { Component, Autowired } from '@malagu/core';
  4. import { RestOperations } from '@malagu/web/lib/common/client/client-protocol';
  5. @Component(JwkSetManager)
  6. export class DefaultJwkSetManager implements JwkSetManager<JWKS.KeyStore> {
  7. protected readonly cacheMap = new Map<string, JWKS.KeyStore>();
  8. @Autowired(RestOperations)
  9. protected readonly restOperations: RestOperations;
  10. async get(jwksUri: string): Promise<JWKS.KeyStore> {
  11. let keyStore = this.cacheMap.get(jwksUri);
  12. if (!keyStore) {
  13. const { data } = await this.restOperations.get(jwksUri);
  14. keyStore = JWKS.asKeyStore(data);
  15. this.cacheMap.set(jwksUri, keyStore);
  16. }
  17. return keyStore;
  18. }
  19. }

属性配置

我们可以通过 malagu.client.config 配置 HTTP 客户端服务对象,配置对象接口定义如下:

  1. export interface AxiosRequestConfig {
  2. url?: string;
  3. method?: Method;
  4. baseURL?: string;
  5. transformRequest?: AxiosTransformer | AxiosTransformer[];
  6. transformResponse?: AxiosTransformer | AxiosTransformer[];
  7. headers?: any;
  8. params?: any;
  9. paramsSerializer?: (params: any) => string;
  10. data?: any;
  11. timeout?: number;
  12. timeoutErrorMessage?: string;
  13. withCredentials?: boolean;
  14. adapter?: AxiosAdapter;
  15. auth?: AxiosBasicCredentials;
  16. responseType?: ResponseType;
  17. xsrfCookieName?: string;
  18. xsrfHeaderName?: string;
  19. onUploadProgress?: (progressEvent: any) => void;
  20. onDownloadProgress?: (progressEvent: any) => void;
  21. maxContentLength?: number;
  22. validateStatus?: ((status: number) => boolean) | null;
  23. maxBodyLength?: number;
  24. maxRedirects?: number;
  25. socketPath?: string | null;
  26. httpAgent?: any;
  27. httpsAgent?: any;
  28. proxy?: AxiosProxyConfig | false;
  29. cancelToken?: CancelToken;
  30. decompress?: boolean;
  31. }

配置示例如下:

  1. malagu:
  2. client:
  3. config:
  4. withCredentials: true
  5. headers:
  6. X-Requested-With: XMLHttpRequest