Skip to content

Commit

Permalink
Fix middleware error handling when using next(error) (#719)
Browse files Browse the repository at this point in the history
(patch)
  • Loading branch information
flybayer committed Jun 29, 2020
1 parent 10146f6 commit 8b2a50d
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 4 deletions.
9 changes: 6 additions & 3 deletions packages/core/src/middleware.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,31 +68,34 @@ describe("handleRequestWithMiddleware", () => {
it("middleware can throw", async () => {
console.log = jest.fn()
console.error = jest.fn()
const forbiddenMiddleware = jest.fn()
const middleware: Middleware[] = [
(_req, _res, _next) => {
throw new Error("test")
},
forbiddenMiddleware,
]

await mockServer(middleware, async (url) => {
const res = await fetch(url)
expect(forbiddenMiddleware).not.toBeCalled()
expect(res.status).toBe(500)
})
})

it("middleware can return error", async () => {
console.log = jest.fn()
const forbiddenMiddleware = jest.fn()
const middleware: Middleware[] = [
(_req, _res, next) => {
return next(new Error("test"))
},
(_req, _res, _next) => {
throw new Error("Remaining middleware should not run if previous has error")
},
forbiddenMiddleware,
]

await mockServer(middleware, async (url) => {
const res = await fetch(url)
expect(forbiddenMiddleware).not.toBeCalled()
expect(res.status).toBe(500)
})
})
Expand Down
6 changes: 5 additions & 1 deletion packages/core/src/middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,11 @@ export function compose(middleware: Middleware[]) {
// last called middleware #
let index = -1

function dispatch(i: number): Promise<void> {
function dispatch(i: number, error?: any): Promise<void> {
if (error) {
return Promise.reject(error)
}

if (i <= index) throw new Error("next() called multiple times")
index = i

Expand Down
2 changes: 2 additions & 0 deletions packages/core/src/ssr-query.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {EnhancedResolverModule} from "./rpc"

describe("ssrQuery", () => {
it("works without middleware", async () => {
console.log = jest.fn()
const resolverModule = (jest.fn().mockImplementation(async (input) => {
await delay(1)
return input
Expand All @@ -33,6 +34,7 @@ describe("ssrQuery", () => {
})

it("works with middleware", async () => {
console.log = jest.fn()
const resolverModule = (jest.fn().mockImplementation(async (input) => {
await delay(1)
return input
Expand Down

0 comments on commit 8b2a50d

Please sign in to comment.