Skip to content

Commit b329900

Browse files
Merge pull request #561 from nicolasmondain/master
ApiClientConfigurator: getCustomMiddleware
2 parents 7da3d8f + 5fae6ac commit b329900

File tree

3 files changed

+48
-3
lines changed

3 files changed

+48
-3
lines changed

package-lock.json

Lines changed: 3 additions & 3 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

src/configuration/ApiClientConfigurator.ts

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -112,9 +112,50 @@ export class ApiClientConfigurator {
112112
)
113113
}
114114

115+
if (config.middleware) {
116+
middleware.push(
117+
...this.getCustomMiddleware<
118+
RequestContextType,
119+
ResponseContextType,
120+
ObservableRequestContextType,
121+
ObservableResponseContextType
122+
>(config, observableRequestContextParam, observableResponseContextParam),
123+
)
124+
}
125+
115126
return middleware
116127
}
117128

129+
protected static getCustomMiddleware<
130+
RequestContextType extends IRequestContext,
131+
ResponseContextType,
132+
ObservableRequestContextType,
133+
ObservableResponseContextType,
134+
>(
135+
config: IConfiguration,
136+
observableRequestContextParam: new (promise: Promise<RequestContextType>) => ObservableRequestContextType,
137+
observableResponseContextParam: new (promise: Promise<ResponseContextType>) => ObservableResponseContextType,
138+
) {
139+
return (
140+
config.middleware
141+
?.filter((m) => m.pre || m.post)
142+
.map((m) => ({
143+
pre: (context: RequestContextType): ObservableRequestContextType => {
144+
if (m.pre && typeof m.pre === 'function') {
145+
return new observableRequestContextParam(Promise.resolve(m.pre(context) as RequestContextType))
146+
}
147+
return new observableRequestContextParam(Promise.resolve(context))
148+
},
149+
post: (context: ResponseContextType): ObservableResponseContextType => {
150+
if (m.post && typeof m.post === 'function') {
151+
return new observableResponseContextParam(Promise.resolve(m.post(context) as ResponseContextType))
152+
}
153+
return new observableResponseContextParam(Promise.resolve(context))
154+
},
155+
})) ?? []
156+
)
157+
}
158+
118159
protected static getHeaderMiddleware<
119160
RequestContextType extends IRequestContext,
120161
ResponseContextType,

src/configuration/IConfiguration.ts

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,4 +12,8 @@ export default interface IConfiguration {
1212
limiterOptions?: Bottleneck.ConstructorOptions
1313
limiterJobOptions?: Bottleneck.JobOptions
1414
httpAgent?: http.Agent | https.Agent
15+
middleware?: Array<{
16+
pre(ctx: unknown): unknown
17+
post(ctx: unknown): unknown
18+
}>
1519
}

0 commit comments

Comments
 (0)