Security News
Input Validation Vulnerabilities Dominate MITRE's 2024 CWE Top 25 List
MITRE's 2024 CWE Top 25 highlights critical software vulnerabilities like XSS, SQL Injection, and CSRF, reflecting shifts due to a refined ranking methodology.
Express as dependency injection container.
Jimpex is an implementation of Express, one of the most popular web frameworks for Node, using Jimple, a Javascript port of Pimple dependency injection container.
A friend who's also web developer brought the idea of start using a dependency injection container on Node, and how Jimple was a great tool for it, and from that moment on I can't think of starting an app without using it. It not only allows you to implement dependency injection on a simple and clean way but it also kind of forces you to have a really good organization of your code.
A couple of months after that, the same friend told me that we should do something similar to Silex, which is based on Pimple, with Express. I ran with the idea and... this project is what I think a mix of Jimple and Express would look like. To be clear, this is not a port of Silex.
- | - |
---|---|
Package | jimpex |
Description | Express as dependency injection container. |
Node Version | >= v10.0.0 |
To create a Jimpex app you would require the Jimpex
class from the package, extend it and define all your services, controllers and middlewares on its boot
method:
const { Jimpex } = require('jimpex');
class MyApp extends Jimpex {
boot() {
// Do all your custom stuff...
}
}
The class constructor has two parameters:
boot
(true
): Whether or not to call the boot
method after initializing the instance.options
({}
): A set of options to customize the app.There are a lot of options to customize an app, so I would recommend you to read the Jimpex Options documentation.
Jimpex, by default, depends on external configuration files and as a base configuration it will try to load ./config/app/app.config.js
. Of course this is extremely configurable through the Jimpex Options.
A configuration file is just a Javascript file that exports an Object, for example:
module.exports = {
port: 2509,
};
If that's who you default configuration file looks like, the app will run on the port
2509
.
To access the app configuration, you just call the appConfiguration
service:
const config = app.get('appConfiguration');
Then you can read its values using .get(setting)
:
console.log(config.get('port'));
// Will log 2509
To more information about how the appConfiguration
service works, you can check its documentation on the wootils repository.
To start the app you need a valid configuration file with a valid port
setting. Check the previous section to more information about it.
Now, Starting the app is as easy as calling start()
:
app.start(() => {
console.log('The app is running!');
});
- Like Express, you can send a callback to be executed after the server starts.
- You also have a
listen
alias with the same signature as express (port and callback) for serverless platforms where you don't manually start the app.
You can also stop the app by calling stop()
:
app.stop();
// Done, the app is not longer running.
To define a service and its provider, you would write your service as a class
or a function
and then wrap it on the provider
function Jimpex provides:
const { provider } = require('jimpex');
// Create your service
class MyService {
constructor(depOne, depTwo);
}
// Define the provider
const myService = provider((app) => {
app.set('myService', () => new MyService(
app.get('depOne'),
app.get('depTwo')
));
});
// Export the service and its provider
module.exports = {
MyService,
myService,
};
You could export just export the provider, but I believe is a good practice to export both in case another part of your app wants to extend the class and overwrite the service on the container.
Then, on you app, you would simple register
the provider:
const { Jimpex } = require('jimpex');
const { myService } = require('...');
class MyApp extends Jimpex {
boot() {
...
this.register(myService);
}
}
Done, your service is now available.
In case you want to create a service that could accept custom setting when instantiated, you can use a "provider creator":
const { providerCreator } = require('jimpex');
// Create your service
class MyService {
constructor(depOne, depTwo, options = {});
}
// Define the provider
const myService = providerCreator((options) => (app) => {
app.set('myService', () => new MyService(
app.get('depOne'),
app.get('depTwo'),
settings
));
});
// Export the service and its provider
module.exports = {
MyService,
myService,
};
The special behavior the creators have, is that you can call them as a function, sending the settings, or just use them on the register
, so it's very important that the settings must be optional:
const { Jimpex } = require('jimpex');
const { myService } = require('...');
class MyApp extends Jimpex {
boot() {
...
this.register(myService);
// or
this.register(myService({ ... }));
}
}
To add controller you need to use the controller
function and return a list of routes:
const { controller } = require('jimpex');
// (Optional) Define a class to organize your route handlers.
class HealthController {
health() {
return (req, res) => {
res.write('Everything works!');
};
}
}
// Define the controller
const healthController = controller((app) => {
const ctrl = new HealthController();
// Get the router service
const router = app.get('router');
// Return the list of routes this controller will handle
return [
router.get('/', ctrl.health()),
];
});
// Export the controller class and the controller itself
module.exports = {
HealthController,
healthController,
};
- You could export just export the controller, but I believe is a good practice to export both in case another part of your app wants to extend the class and mount a new route withs its inherit functionalities.
- The function inside the
controller
wrapper won't be called until the app is started. In case you are wondering about the lazy loading of the services that you may inject.
Then, on you app, you would mount
the controller:
const { Jimpex } = require('jimpex');
const { healthController } = require('...');
class MyApp extends Jimpex {
boot() {
...
this.mount('/health', healthController);
}
}
Like with _"providers creators", you can define controllers that accept custom settings when instantiated, using a "controller creator":
const { controllerCreator } = require('jimpex');
// (Optional) Define a class to organize your route handlers.
class HealthController {
constructor(settings = {});
health() {
return (req, res) => {
res.write('Everything works!');
};
}
}
// Define the controller
const healthController = controllerCreator((settings) => (app) => {
const ctrl = new HealthController(settings);
// Get the router service
const router = app.get('router');
// Return the list of routes this controller will handle
return [
router.get('/', ctrl.health()),
];
});
// Export the controller class and the controller itself
module.exports = {
HealthController,
healthController,
};
The special behavior the creators have, is that you can call them as a function, sending the settings, or just use them with mount
as regular controllers; and since they can be used as regular controllers, it's very important that the settings are optional:
const { Jimpex } = require('jimpex');
const { healthController } = require('...');
class MyApp extends Jimpex {
boot() {
...
this.mount('/health', healthController);
// or
this.mount('/health', healthController({ ... }));
}
}
To add a new middleware you need to use the middleware
function and return a function:
const { middlware } = require('jimpex');
// Define your middleware function (or class if it gets more complex)
const greetingsMiddleware = () => (req, res, next) => {
console.log('Hello!');
};
// Define the middleware
const greetings = middleware(() => greetingsMiddleware());
// Export the function and the middleware
module.exports = {
greetingsMiddleware,
greetings,
};
You could export just export the provider, but I believe is a good practice to export both in case another part of your app wants to extend the class or use the function.
Then, on you app, you would use
the controller:
const { Jimpex } = require('jimpex');
const { greetings } = require('...');
class MyApp extends Jimpex {
boot() {
...
this.use(greetings);
}
}
Like with controllers and providers, you can also create a middleware that can accept settings when instantiated, with a "middleware creator":
const { middlwareCreator } = require('jimpex');
// Define your middleware function (or class if it gets more complex)
const greetingsMiddleware = (message = 'Hello!') => (req, res, next) => {
console.log(message);
};
// Define the middleware
const greetings = middlewareCreator((message) => greetingsMiddleware(message));
// Export the function and the middleware
module.exports = {
greetingsMiddleware,
greetings,
};
The special behavior the creators have, is that you can call them as a function, sending the settings, or just register them with use
as regular middlewares, so it's very important that the settings must be optional:
const { Jimpex } = require('jimpex');
const { greetings } = require('...');
class MyApp extends Jimpex {
boot() {
...
this.use(greetings);
// or
this.use(greetings('Howdy!'));
}
}
Jimpex comes with a few services, middlewares and controllers that you can import and use on your app, some of them are activated by default on the options, but others you have to implement manually:
static
middleware.Read more about the built-in controllers
Strict-Transport-Security
header and includes it on every response.409
error if the request doesn't have a version parameter with the same version as the one on the configuration.Read more about the built-in controllers
Error
but with support for context information. It can be used to customize the error handler responses.Authorization
header.window
variable.Read more about the built-in services
The service also implements a few other services from the wootils as core utilities:
appLogger
: The logger service.environmentUtils
: The service that reads the environment variables.packageInfo
: The app package.json information.pathUtils
: The service to build paths relative to the project root directory.rootRequire
: The service to make requires relatives to the project root directory.events
: To handle the app events.Task | Description |
---|---|
yarn test | Run the project unit tests. |
yarn run lint | Lint the modified files. |
yarn run lint:full | Lint the project code. |
yarn run docs | Generate the project documentation. |
yarn run todo | List all the pending to-do's. |
I use Jest with Jest-Ex to test the project. The configuration file is on ./.jestrc
, the tests and mocks are on ./tests
and the script that runs it is on ./utils/scripts/test
.
I use ESlint to validate all our JS code. The configuration file for the project code is on ./.eslintrc
and for the tests on ./tests/.eslintrc
(which inherits from the one on the root), there's also an ./.eslintignore
to ignore some files on the process, and the script that runs it is on ./utils/scripts/lint
.
I use ESDoc to generate HTML documentation for the project. The configuration file is on ./.esdocrc
and the script that runs it is on ./utils/scripts/docs
.
I use @todo
comments to write all the pending improvements and fixes, and Leasot to generate a report. The script that runs it is on ./utils/scripts/todo
.
FAQs
Express as dependency injection container.
The npm package jimpex receives a total of 211 weekly downloads. As such, jimpex popularity was classified as not popular.
We found that jimpex demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 0 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
MITRE's 2024 CWE Top 25 highlights critical software vulnerabilities like XSS, SQL Injection, and CSRF, reflecting shifts due to a refined ranking methodology.
Security News
In this segment of the Risky Business podcast, Feross Aboukhadijeh and Patrick Gray discuss the challenges of tracking malware discovered in open source softare.
Research
Security News
A threat actor's playbook for exploiting the npm ecosystem was exposed on the dark web, detailing how to build a blockchain-powered botnet.