Skip to content

Commit

Permalink
fix: handle HTTPException
Browse files Browse the repository at this point in the history
  • Loading branch information
BarryThePenguin committed Jun 27, 2024
1 parent 48fd541 commit 0acd56c
Show file tree
Hide file tree
Showing 3 changed files with 54 additions and 6 deletions.
38 changes: 38 additions & 0 deletions src/adapter/cloudflare-pages/handler.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { getCookie } from '../../helper/cookie'
import { Hono } from '../../hono'
import { HTTPException } from '../../http-exception'
import type { EventContext } from './handler'
import { handle, handleMiddleware } from './handler'

Expand Down Expand Up @@ -121,4 +122,41 @@ describe('Middleware adapter for Cloudflare Pages', () => {

expect(await res.json()).toEqual('From Cloudflare Pages')
})

it('Should handle a HTTPException by returning error.getResponse()', async () => {
const request = new Request('http://localhost/api/foo')
const env = {
TOKEN: 'HONOISCOOL',
}
const handler = handleMiddleware(() => {
const res = new Response('Unauthorized', { status: 401 })
throw new HTTPException(401, { res })
})

const next = vi.fn().mockResolvedValue(Response.json('From Cloudflare Pages'))
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
const res = await handler({ request, env, next })

expect(next).not.toHaveBeenCalled()

expect(res.status).toBe(401)
expect(await res.text()).toBe('Unauthorized')
})

it('Should rethrow an Error', async () => {
const request = new Request('http://localhost/api/foo')
const env = {
TOKEN: 'HONOISCOOL',
}
const handler = handleMiddleware(async () => {
throw new Error('Something went wrong')
})

const next = vi.fn().mockResolvedValue(Response.json('From Cloudflare Pages'))
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
await expect(handler({ request, env, next })).rejects.toThrowError('Something went wrong')
expect(next).not.toHaveBeenCalled()
})
})
20 changes: 15 additions & 5 deletions src/adapter/cloudflare-pages/handler.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Context } from '../../context'
import type { Hono } from '../../hono'
import { HonoRequest } from '../../request'
import { HTTPException } from '../../http-exception'
import type { Env, Input, MiddlewareHandler } from '../../types'

// Ref: https://github.com/cloudflare/workerd/blob/main/types/defines/pages.d.ts
Expand Down Expand Up @@ -48,14 +48,24 @@ export function handleMiddleware<E extends Env = any, P extends string = any, I
middleware: MiddlewareHandler<E, P, I>
): PagesFunction {
return async (executionCtx) => {
const context = new Context(new HonoRequest(executionCtx.request), {
const context = new Context(executionCtx.request, {
env: executionCtx.env,
executionCtx,
})

const response = await middleware(context, async () => {
context.res = await executionCtx.next()
})
let response: Response | void = undefined

try {
response = await middleware(context, async () => {
context.res = await executionCtx.next()
})
} catch (error) {
if (error instanceof HTTPException) {
response = error.getResponse()
} else {
throw error
}
}

return response ?? context.res
}
Expand Down
2 changes: 1 addition & 1 deletion src/adapter/cloudflare-pages/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,5 @@
* Cloudflare Pages Adapter for Hono.
*/

export { handle, serveStatic } from './handler'
export { handle, handleMiddleware, serveStatic } from './handler'
export type { EventContext } from './handler'

0 comments on commit 0acd56c

Please sign in to comment.