Skip to content

Commit

Permalink
Merge pull request #40 from ogd-software/master
Browse files Browse the repository at this point in the history
Make async/wait for middleware beforeFilters and afterFilters possible
  • Loading branch information
richmolj authored Aug 14, 2019
2 parents d271168 + 5ee9dcc commit e64c145
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 7 deletions.
18 changes: 12 additions & 6 deletions src/middleware-stack.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
export type BeforeFilter = (requestUrl: string, options: RequestInit) => void
export type AfterFilter = (response: Response, json: JSON) => void

async function asyncForEach(array: Array<Function>, callback: Function) {
for (let index = 0; index < array.length; index += 1) {
await callback(array[index], index, array)
}
}

export class MiddlewareStack {
private _beforeFilters: BeforeFilter[] = []
private _afterFilters: AfterFilter[] = []
Expand All @@ -18,15 +24,15 @@ export class MiddlewareStack {
return this._afterFilters
}

beforeFetch(requestUrl: string, options: RequestInit) {
this._beforeFilters.forEach(filter => {
filter(requestUrl, options)
async beforeFetch(requestUrl: string, options: RequestInit) {
await asyncForEach(this._beforeFilters, async (filter: Function) => {
await filter(requestUrl, options)
})
}

afterFetch(response: Response, json: JSON) {
this._afterFilters.forEach(filter => {
filter(response, json)
async afterFetch(response: Response, json: JSON) {
await asyncForEach(this._afterFilters, async (filter: Function) => {
await filter(response, json)
})
}
}
2 changes: 1 addition & 1 deletion src/request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ export class Request {

private async _fetch(url: string, options: RequestInit): Promise<any> {
try {
this.middleware.beforeFetch(url, options)
await this.middleware.beforeFetch(url, options)
} catch (e) {
throw new RequestError(
"beforeFetch failed; review middleware.beforeFetch stack",
Expand Down

0 comments on commit e64c145

Please sign in to comment.