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: expose full Koa context to options #86

Merged
merged 1 commit into from
Dec 13, 2023
Merged
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
37 changes: 23 additions & 14 deletions src/use/koa.ts
Original file line number Diff line number Diff line change
@@ -1,25 +1,30 @@
import type { Middleware, Response } from 'koa';
import type {
Middleware,
ParameterizedContext,
DefaultState,
DefaultContext,
} from 'koa';
import type { IncomingMessage } from 'http';
import {
createHandler as createRawHandler,
HandlerOptions as RawHandlerOptions,
OperationContext,
} from '../handler';

/**
* @category Server/koa
*/
export interface RequestContext {
res: Response;
}

/**
* Handler options when using the koa adapter.
*
* @category Server/koa
*/
export type HandlerOptions<Context extends OperationContext = undefined> =
RawHandlerOptions<IncomingMessage, RequestContext, Context>;
export type HandlerOptions<
Context extends OperationContext = undefined,
KoaState = DefaultState,
KoaContext = DefaultContext,
> = RawHandlerOptions<
IncomingMessage,
ParameterizedContext<KoaState, KoaContext>,
Context
>;

/**
* The ready-to-use handler for [Koa](https://expressjs.com).
Expand Down Expand Up @@ -58,9 +63,13 @@ export type HandlerOptions<Context extends OperationContext = undefined> =
*
* @category Server/koa
*/
export function createHandler<Context extends OperationContext = undefined>(
options: HandlerOptions<Context>,
): Middleware {
export function createHandler<
Context extends OperationContext = undefined,
KoaState = DefaultState,
KoaContext = DefaultContext,
>(
options: HandlerOptions<Context, KoaState, KoaContext>,
): Middleware<KoaState, KoaContext> {
const handler = createRawHandler(options);
return async function requestListener(ctx) {
const [body, init] = await handler({
Expand All @@ -84,7 +93,7 @@ export function createHandler<Context extends OperationContext = undefined>(
});
},
raw: ctx.req,
context: { res: ctx.response },
context: ctx,
});
ctx.response.status = init.status;
ctx.response.message = init.statusText;
Expand Down