Inversion of Control for controllers #10
-
First, I'm glad that this project starts to show signs of life again, thanks! I'm pretty new to oas-tools and modern js/ts development. I don't miss a full blown DI containers and so on but I'm wondering, how do I achieve basic Inversion of Control for OAS Tools controllers? From all the examples I see it wants me to import the dependencies (services, configs, ...) in the controller module, but I want them to be injectable during creation so I can mock them in tests. Can this be achieved? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Unfortunately, DI is not possible in OAS Tools currently. However, since the framework is flexible enough, you could implement a basic DI that can serve your purpose. To do that, you need to create a new external module that replaces the router middleware and add it to the OAS Tools chain through
// newRouter.js
import { OASBase, errors, logger } from "@oas-tools/commons";
import { commons } from "../../utils/index.js";
import { pathToFileURL } from "url";
export class OASRouter extends OASBase {
constructor(oasFile, middleware) {
super(oasFile, middleware);
}
static async initialize(oasFile, config) {
const controllers = await OASRouter.#loadControllers(oasFile, config);
return new OASRouter(oasFile, (req, res, _next) => {
const requestPath = req.route.path;
const method = req.method;
controllers[requestPath][method](req, res);
});
}
...
// call controller
controllers[requestPath][method](req, res, config.di);
export function DIController(req, res, deps) {
// Do something
}
// .oastoolsrc
{
...
"middleware": {
"router": {
"disable": true
}
}
} import { NewRouter } from './newRouter.js';
const depsCfg= {
di: {
dep1: import('some-dependency',
dep2: import('another-dependency')
}
}
oasTools.use(NewRouter, depsCfg, 4);
oasTools.initialize(app).then(() => ...) I hope you find this workaround useful. There are many other ways to implement DI, like adding your dependencies to the |
Beta Was this translation helpful? Give feedback.
Unfortunately, DI is not possible in OAS Tools currently. However, since the framework is flexible enough, you could implement a basic DI that can serve your purpose. To do that, you need to create a new external module that replaces the router middleware and add it to the OAS Tools chain through
oasTools.use( )
. You could then inject your dependencies through this new module's configuration: