In node.js, sometimes we need to initialize some async components before the application starts serving HTTP requests.
(async () => {
const db = await getDbConn();
let module = new ContainerModule(
(bind: interfaces.Bind, unbind: interfaces.Unbind) => {
bind("db").toContainerValue(db);
}
);
let container = new Container();
container.load(module);
let server = new InversifyExpressServer(container);
server.setConfig((app) => {
// add body parser
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
});
let app = server.build();
app.listen(3000);
})();
The new API introduces 2 breaking changes:
- Container modules use now an async function
- The container.load method is now async
The new API introduces a new kind of module known as AsyncContainerModule and a new container method named loadAsync:
let module = new AsyncContainerModule(
async (bind: interfaces.Bind, unbind: interfaces.Unbind) => { // async!
const db = await getDbConn();
bind("db").toContainerValue(db);
}
);
(async () => {
let container = new Container();
await container.loadAsync(module); // await!
let server = new InversifyExpressServer(container);
server.setConfig((app) => {
// add body parser
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
});
let app = server.build();
app.listen(3000);
})();
If possible, keep old sync API please. My package is fully sync and i very don't want to make it async.
@sanex3339 see updated API. It will be blackguards compatible.
Amazing
Great !
Most helpful comment
@sanex3339 see updated API. It will be blackguards compatible.