Skip to content

Commit

Permalink
Merge pull request #64 from dlgoodchild/master
Browse files Browse the repository at this point in the history
feat: add `importControllers` and allow passing router to `loadControllers`
  • Loading branch information
jeffijoe authored Oct 13, 2023
2 parents f01658e + 1477654 commit bae8673
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 5 deletions.
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`.
Expand Down
20 changes: 16 additions & 4 deletions src/controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
}

/**
Expand Down

0 comments on commit bae8673

Please sign in to comment.