Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Merged
merged 1 commit into from
Sep 8, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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