Skip to content

Commit

Permalink
feat(use/koa): expose full Koa context to options (#86)
Browse files Browse the repository at this point in the history
  • Loading branch information
henrinormak committed Dec 13, 2023
1 parent d0457c2 commit b37a6f9
Showing 1 changed file with 23 additions and 14 deletions.
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

0 comments on commit b37a6f9

Please sign in to comment.