0
0
mirror of https://github.com/honojs/hono.git synced 2024-11-21 18:18:57 +01:00

feat(cloudflare-pages): enable c.env.eventContext in handleMiddleware (#3332)

This commit is contained in:
Yusuke Wada 2024-09-08 15:45:53 +09:00 committed by GitHub
parent 5a25e33e93
commit 8e56989cde
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 24 additions and 4 deletions

View File

@ -230,6 +230,18 @@ describe('Middleware adapter for Cloudflare Pages', () => {
await expect(handler(eventContext)).rejects.toThrowError('Something went wrong')
expect(next).not.toHaveBeenCalled()
})
it('Should set the data in eventContext.data', async () => {
const next = vi.fn()
const eventContext = createEventContext({ next })
const handler = handleMiddleware(async (c, next) => {
c.env.eventContext.data.user = 'Joe'
await next()
})
expect(eventContext.data.user).toBeUndefined()
await handler(eventContext)
expect(eventContext.data.user).toBe('Joe')
})
})
describe('serveStatic()', () => {

View File

@ -9,7 +9,7 @@ import type { BlankSchema, Env, Input, MiddlewareHandler, Schema } from '../../t
type Params<P extends string = any> = Record<P, string | string[]>
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export type EventContext<Env = {}, P extends string = any, Data = {}> = {
export type EventContext<Env = {}, P extends string = any, Data = Record<string, unknown>> = {
request: Request
functionPath: string
waitUntil: (promise: Promise<unknown>) => void
@ -43,12 +43,20 @@ export const handle =
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function handleMiddleware<E extends Env = any, P extends string = any, I extends Input = {}>(
middleware: MiddlewareHandler<E, P, I>
export function handleMiddleware<E extends Env = {}, P extends string = any, I extends Input = {}>(
middleware: MiddlewareHandler<
E & {
Bindings: {
eventContext: EventContext
}
},
P,
I
>
): PagesFunction<E['Bindings']> {
return async (executionCtx) => {
const context = new Context(executionCtx.request, {
env: executionCtx.env,
env: { ...executionCtx.env, eventContext: executionCtx },
executionCtx,
})