Express Plugin
The Express Plugin provides tools to work with the Express Framework to create Express applications in a better and organized way.
The plugin exposes decorators for creating controllers, route handlers, and middlewares that wraps the Express API.
This plugin should be used with Injex's Node runtime.
Installation
You can install the Env Plugin via NPM or Yarn.
- npm
- Yarn
You should also make sure Express
is installed on your project.
Initialization
Creating the plugin and passing it to the runtime container config object
Configurations
name
The express application instance name, as it will be used in the runtime container for later injection.
- Type:
string
- Default:
expressApp
- Required:
false
app
If you already have an express instance in your application, you can pass it to the app
config option so the plugin will use it.
For example:
- Type:
ExpressApplication instance
- Default: null
- Required:
false
createAppCallback
If you don't provide the app
config option, the Express Plugin will create an Express app instance for you. You can pass in the createAppCallback
if you want to hook up the application instance with custom middleware or listen to a network port.
For example:
- Type:
Function
- Default:
function(app: Application) { }
- Required:
false
Usage
As mentioned above, the Express plugin exposes decorators to handle routes and middlewares inside a controller. A controller is a collection of route handlers related to a specific domain in your application. An exciting part about controllers is that they respond to the @singleton()
decorator so that you can create a singleton controller or a factory-based controller made for each request.
@controller()
Defines a class and mark it as a controller. If the @singleton()
decorator is also used, only one controller will be created for all requests; otherwise, a controller instance will be created for each request.
@get()
, @post()
, @patch()
, @put()
, @del()
HTTP method handler decorators to define route handlers inside a controller.
@middleware()
Define a middleware or a list of chainable middlewares on a controller route handler. A middleware is a class that implements the IMiddleware
interface.
Note that you can pass an array of middlewares (@middleware([ ... ])
); in that case, the middlewares get called from left to right. If a middleware failed with an error, the route handler function would not be triggered.
A full example
If you want a quick demo to play with, check out the express example in the examples section.