From 1477654f2fd03fc4b4b329b2b4b1ed157dfc9acb Mon Sep 17 00:00:00 2001 From: Dave Goodchild Date: Fri, 13 Oct 2023 22:54:56 +0200 Subject: [PATCH] feat: add `importControllers` and allow passing router to `loadControllers` --- README.md | 3 ++- src/controller.ts | 20 ++++++++++++++++---- 2 files changed, 18 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 26587bd..4fb26cb 100644 --- a/README.md +++ b/README.md @@ -359,7 +359,8 @@ The package exports everything from `awilix-router-core` as well as the followin - `scopePerRequest(container)`: creates a scope per request. - `controller(decoratedClassOrController)`: registers routes and delegates to Koa Router. -- `loadControllers(pattern, opts)`: loads files matching a glob pattern and registers their exports as controllers. +- `importControllers(router, pattern, opts)`: imports files matching a glob pattern, registers their exports as controllers, applying them to the supplied koa-router +- `loadControllers(pattern, opts, router)`: loads files matching a glob pattern and registers their exports as controllers and returns a middleware for use with Koa - `makeInvoker(functionOrClass, opts)(methodName)`: using `isClass`, calls either `makeFunctionInvoker` or `makeClassInvoker`. - `makeClassInvoker(Class, opts)(methodName)`: resolves & calls `methodName` on the resolved instance, passing it `ctx` and `next`. - `makeFunctionInvoker(function, opts)(methodName)`: resolves & calls `methodName` on the resolved instance, passing it `ctx` and `next`. diff --git a/src/controller.ts b/src/controller.ts index 5b7b356..eb23a6e 100644 --- a/src/controller.ts +++ b/src/controller.ts @@ -43,19 +43,31 @@ export function controller( } /** - * Loads controllers for the given pattern. + * Imports and prepares controllers for the given pattern, applying them to the supplied router * + * @param router * @param pattern * @param opts */ -export function loadControllers(pattern: string, opts?: IOptions): Middleware { - const router = new Router() +export function importControllers(router: Router, pattern: string, opts?: IOptions): void { findControllers(pattern, { ...opts, absolute: true, }).forEach(_registerController.bind(null, router)) +} - return compose([router.routes(), router.allowedMethods()]) as any +/** + * Loads controllers for the given pattern and returns a koa-compose'd Middleware + * This return value must be used with `Koa.use`, and is incompatible with `Router.use` + * + * @param pattern + * @param opts + * @param router + */ +export function loadControllers(pattern: string, opts?: IOptions, router?: Router): Middleware { + const r = router || new Router() + importControllers(r, pattern, opts) + return compose([r.routes(), r.allowedMethods()]) as any } /**