20
loading...
This website collects cookies to deliver better user experience
const UserService = require('./UserService')
class CustomerService{
create() {
UserService.create();
console.log('Create Customer');
}
}
module.exports = new CustomerService;
const CustomerService = require('./CustomerService')
class UserService {
create() {
console.log('Create user');
}
get() {
let customer = CustomerService.get();
console.log({customer});
}
}
module.exports = new UserService;
const CustomerService = require('./services/CustomerService');
const UserService = require('./services/UserService');
CustomerService.create();
UserService.get();
const fs = require('fs');
const path = require('path');
const basename = path.basename(__filename);
const services = {};
// here we're going to read all files inside _services_ folder.
fs
.readdirSync(__dirname)
.filter(file => {
return (file.indexOf('.') !== 0) &&
(file !== basename) &&
(file.slice(-3) === '.js') &&
(file.slice(-8) !== '.test.js') &&
(file !== 'Service.js')
}).map(file => {
// we're are going to iterate over the files name array that we got, import them and build an object with it
const service = require(path.join(__dirname,file));
services[service.constructor.name] = service;
})
// this functionality inject all modules inside each service, this way, if you want to call some other service, you just call it through the _this.service.ServiceClassName_.
Object.keys(services).forEach(serviceName => {
if(services[serviceName].associate) {
services[serviceName].associate(services);
}
})
module.exports = services;
class Service {
associate(services) {
this.services = services;
}
}
module.exports = Service;
const Service = require('./Service')
class CustomerService extends Service{
create() {
this.services.UserService.create();
console.log('Create Customer');
}
}
module.exports = new CustomerService;
// now you only import the Service.js
const Service = require('./Service.js')
class UserService extends Service{
create() {
console.log('Create user');
}
get() {
// now we call the service the we want this way
let customer = this.services.CustomerService.get();
console.log({customer});
}
}
module.exports = new UserService;
// now we only import the index.js (when you don't set the name of the file that you're intending to import, automatically it imports index.js)
const {CustomerService, UserService} = require('./services/')
// and we call this normally
CustomerService.create();
UserService.get();