Created
August 13, 2021 16:35
-
-
Save Lxxyx/1b456ebca17f6459d1da3a2b1e30232d to your computer and use it in GitHub Desktop.
useApiClientBuilder.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import { | |
| useApiClientMatcher, | |
| createApiClientMatcher, | |
| ProjectConfig | |
| } from '@midwayjs/hooks-core' | |
| import { request } from '@midwayjs/hooks/request' | |
| interface ApiMetadata { | |
| file: string | |
| method: string | |
| fn: Function | |
| functionId: string | |
| route: any | |
| } | |
| // 支持多 Client | |
| const FCMatcher = createApiClientMatcher() | |
| .route( | |
| { mtop: true }, | |
| { | |
| client: 'lib-mtop', | |
| metadata: { | |
| fc: true | |
| } | |
| } | |
| ) | |
| .match((meta: ApiMetadata) => { | |
| if (meta.file.includes('hsf')) { | |
| return { | |
| client: 'lib-hsf', | |
| metadata: { | |
| fc_hsf: true, | |
| env: 'daily' | |
| } | |
| } | |
| } | |
| }) | |
| useApiClientMatcher(FCMatcher) | |
| const MiniProgramMatcher = createApiClientMatcher() | |
| .route( | |
| { | |
| event: 'wechat-miniprogram' | |
| }, | |
| { | |
| client: '@midwayjs/hooks-miniprogram-client' | |
| } | |
| ) | |
| .match((metadata: ApiMetadata) => { | |
| if (route.event === 'alipay-miniprogram') { | |
| return { | |
| client: 'alipay-miniprogram', | |
| metadata: { | |
| isAlipayMiniProgram: true | |
| } | |
| } | |
| } | |
| }) | |
| const HttpMatcher = createApiClientMatcher() | |
| .match((metadata: ApiMetadata, projectConfig: ProjectConfig) => { | |
| if (metadata.route.basePath) { | |
| const HttpRouter = new HttpRouter('/', projectConfig) | |
| return { | |
| client: '@midwayjs/hooks-core/request', | |
| metadata: { | |
| url: HttpRouter.getHTTPPath(metadata.file, metadata.method, true), | |
| method: '*', | |
| } | |
| } | |
| } | |
| }) | |
| useApiClientMatcher(HttpMatcher) | |
| request.use((ctx, next) => { | |
| console.log(ctx.request.url) | |
| await next() | |
| console.log(ctx.response.url) | |
| }) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment