Skip to content

Commit

Permalink
feat(cloudflare-pages): enable c.env.eventContext in `handleMiddlew…
Browse files Browse the repository at this point in the history
…are` (#3332)
  • Loading branch information
yusukebe authored Sep 8, 2024
1 parent 5a25e33 commit 8e56989
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 4 deletions.
12 changes: 12 additions & 0 deletions src/adapter/cloudflare-pages/handler.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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()', () => {
Expand Down
16 changes: 12 additions & 4 deletions src/adapter/cloudflare-pages/handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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,
})

Expand Down

0 comments on commit 8e56989

Please sign in to comment.