Skip to content

Commit

Permalink
feat(koa): support middleware
Browse files Browse the repository at this point in the history
  • Loading branch information
thonatos committed Jan 23, 2024
1 parent 9558755 commit 496d764
Show file tree
Hide file tree
Showing 6 changed files with 43 additions and 30 deletions.
4 changes: 3 additions & 1 deletion packages/apps/artusx-api/src/app/controller/home.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,14 @@ import { ArtusInjectEnum, Inject } from '@artus/core';
import { GET, POST, HTTPController, Middleware } from '../types';
import type { ArtusxContext } from '../types';

import traceTime from '../middleware/traceTime';

@HTTPController()
export default class HomeController {
@Inject(ArtusInjectEnum.Config)
config: Record<string, any>;

@Middleware([traceTime])
@GET('/')
async home(ctx: ArtusxContext) {
ctx.body = 'home';
Expand All @@ -19,7 +22,6 @@ export default class HomeController {
};
}

@Middleware([])
@GET('/can-be-get')
@POST('/post')
async postInfo(ctx: ArtusxContext) {
Expand Down
4 changes: 2 additions & 2 deletions packages/apps/artusx-api/src/app/middleware/checkAuth.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { ArtusxContext, ArtusxNext } from '../types';

export default async function checkAuth(ctx: ArtusxContext, next: ArtusxNext): Promise<void> {
const { data } = ctx.output;
const { data } = ctx.context.output;
data.authed = false;
console.log('middleware - checkAuth', data);
console.log('middleware - checkAuth', ctx.context);
await next();
}
7 changes: 7 additions & 0 deletions packages/apps/artusx-api/src/app/middleware/traceTime.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { ArtusxContext, ArtusxNext } from '../types';

export default async function traceTime(_ctx: ArtusxContext, next: ArtusxNext): Promise<void> {
console.time('trace');
await next();
console.timeEnd('trace');
}
15 changes: 7 additions & 8 deletions packages/plugins/koa/src/decorator.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { addTag, Injectable, ScopeEnum } from '@artus/core';
import { ControllerMetadata, MiddlewareMetadata, RouteMetadata, HTTPMethod } from './types';

import { ControllerMetadata, MiddlewareMetadata, RouteMetadata, HTTPMethod, KoaMiddleware } from './types';

export const ROUTER_METADATA = Symbol.for('ROUTE_METADATA');
export const MIDDLEWARE_METADATA = Symbol.for('MIDDLEWARE_METADATA');

Expand All @@ -18,16 +20,13 @@ export function HTTPController(prefix?: string) {
};
}

export const Middleware = (middlewares: string[]) => {
export const Middleware = (middlewares: KoaMiddleware[]) => {
return (_target: object, _key: string | symbol, descriptor: TypedPropertyDescriptor<any>) => {
const middlewareMetadataList: MiddlewareMetadata[] =
Reflect.getMetadata(MIDDLEWARE_METADATA, descriptor.value) ?? [];

middlewareMetadataList.push({
const middlewareMetadata: MiddlewareMetadata = {
middlewares
});
};

Reflect.defineMetadata(MIDDLEWARE_METADATA, middlewareMetadataList, descriptor.value);
Reflect.defineMetadata(MIDDLEWARE_METADATA, middlewareMetadata, descriptor.value);

return descriptor;
};
Expand Down
41 changes: 23 additions & 18 deletions packages/plugins/koa/src/lifecycle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,26 +58,31 @@ export default class ApplicationHttpLifecycle implements ApplicationLifecycle {
private registerRoute(
controllerMetadata: ControllerMetadata,
routeMetadataList: RouteMetadata[],
_middlewareMetadataList: MiddlewareMetadata[],
middlewareMetadata: MiddlewareMetadata,
handler: ArtusxHandler
) {
for (const routeMetadata of routeMetadataList) {
const routePath = path.normalize((controllerMetadata.prefix ?? '/') + routeMetadata.path);

this.router.register(routePath, [routeMetadata.method], async (ctx, next) => {
// run pipeline
const input = new Input();
input.params.ctx = ctx;
input.params.req = ctx.req;
input.params.res = ctx.res;

const context = new Context(input);
await this.pipeline.run(context);
ctx.context = context;

// handle request
await handler(ctx as unknown as ArtusxContext, next);
});
const middlewares = middlewareMetadata.middlewares || [];
this.router.register(
routePath,
[routeMetadata.method],
[
...middlewares,

async (ctx, next) => {
// run pipeline
const input = new Input();
const context = new Context(input);
ctx.context = context;

await this.pipeline.run(ctx as any);

// handle request
await handler(ctx as unknown as ArtusxContext, next);
}
]
);
}
}

Expand All @@ -97,15 +102,15 @@ export default class ApplicationHttpLifecycle implements ApplicationLifecycle {
const routeMetadataList: RouteMetadata[] =
Reflect.getMetadata(ROUTER_METADATA, handlerDescriptor.value) ?? [];

const middlewareMetadataList: MiddlewareMetadata[] =
const middlewareMetadata: MiddlewareMetadata =
Reflect.getMetadata(MIDDLEWARE_METADATA, handlerDescriptor.value) ?? [];

if (routeMetadataList.length === 0) continue;

this.registerRoute(
controllerMetadata,
routeMetadataList,
middlewareMetadataList,
middlewareMetadata,
controller[key].bind(controller)
);
}
Expand Down
2 changes: 1 addition & 1 deletion packages/plugins/koa/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ export interface ControllerMetadata {
}

export interface MiddlewareMetadata {
middlewares: string[];
middlewares: KoaMiddleware[];
}

export interface RouteMetadata {
Expand Down

0 comments on commit 496d764

Please sign in to comment.