Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Handle request retry or re-routing in middleware.afterFilters #100

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 13 additions & 3 deletions src/middleware-stack.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
export type BeforeFilter = (requestUrl: string, options: RequestInit) => void
export type AfterFilter = (response: Response, json: JSON) => void
export type AfterFilter = (
response: Response,
json: JSON,
requestOptions: RequestInit
) => void

async function asyncForEach(array: Array<Function>, callback: Function) {
for (let index = 0; index < array.length; index += 1) {
Expand All @@ -10,10 +14,12 @@ async function asyncForEach(array: Array<Function>, callback: Function) {
export class MiddlewareStack {
private _beforeFilters: BeforeFilter[] = []
private _afterFilters: AfterFilter[] = []
public newResponse: Response | null = null

constructor(before: BeforeFilter[] = [], after: AfterFilter[] = []) {
this._beforeFilters = before
this._afterFilters = after
this.newResponse = null
}

get beforeFilters() {
Expand All @@ -30,9 +36,13 @@ export class MiddlewareStack {
})
}

async afterFetch(response: Response, json: JSON) {
async afterFetch(
response: Response,
json: JSON,
requestOptions: RequestInit
) {
await asyncForEach(this._afterFilters, async (filter: Function) => {
await filter(response, json)
await filter(response, json, requestOptions)
})
}
}
14 changes: 11 additions & 3 deletions src/request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -109,9 +109,9 @@ export class Request {
throw new ResponseError(null, e.message, e)
}

await this._handleResponse(response, options)
const middlewareResponse = await this._handleResponse(response, options)

return response
return middlewareResponse || response
}

private async _handleResponse(
Expand All @@ -133,7 +133,13 @@ export class Request {
}

try {
await this.middleware.afterFetch(response, json)
await this.middleware.afterFetch(response, json, requestOptions)

if (this.middleware.newResponse) {
response = this.middleware.newResponse.clone()
json = await response.json()
this.middleware.newResponse = null
}
} catch (e) {
// afterFetch middleware failed
throw new ResponseError(
Expand All @@ -156,6 +162,8 @@ export class Request {
}

;(<any>response).jsonPayload = json

return response
}
}

Expand Down