I have been following component based strucutre for my projects and I have clone the repo for this purpose listed here
Everything is fine and testable except services.
So I decided to use awilix to inject dependencies in services.
This is what I tried.
I created a container.js
file in the loaders
.
const awilix = require('awilix');
const db = require('../db');
const AuthService = require('../components/auth/auth.service');
const container = awilix.createContainer({
injectionMode: awilix.InjectionMode.PROXY,
});
function setup() {
container.register({
db: awilix.asValue(db),
doGetAllService: awilix.asValue(AuthService.doRegister),
});
}
module.exports = {
container,
setup,
};
I invoked this container in app.js
as below.
const express = require('express');
const app = express();
const cors = require('cors');
// load environment config variables
require('dotenv').config();
require('./loaders/container').setup();
...
In the doc it says, the first argument will be injected dependencies. But when I do console.log
I still get undefined.
const doRegister = async (opts, { username, password }) => {
console.log(opts);
const user = await User.create({
username,
password,
role_id: 1, // assign role id here
});
return user;
};
For entire folder structure and source conde please go through the repo.