The "middleware" app maintains a library of express middleware for easy insertion into routes. It also defines some standard middleware you can easily plug in.
When the "middleware" service loads, it connects to the MongoDB (for session)
and defines some standard middleware. It also reads the file middleware.js
from each installed app to add more middleware to its library.
The middleware library works similar to the app library, in that middleware functions are tracked by a name, but aliases can be applied to easily reference groups of middleware. The existing middleware and middleware group aliases are documented a little further below.
The method middleware(...names)
will return a list of middleware functions,
for easy insertion into a route. Note that in the root level of a router.js
file (read by the "routes" app), the "middleware" service will have been loaded
but not mounted, so you will have to access it via App.$('middleware')
instead of App.$middleware
.
// apps/my_custom_app/routes.js
const express = require('express');
const App = require('@carolina/core');
const router = express.Router();
// use standard and CSRF (csurf) middleware for this router
router.use(App.$('middleware').middleware(':standard', 'csrf'));
module.exports = { router };
The middleware service also allows you to access a session by ID via the
getSession(sessionId)
method. Generally,
this is not necessary as the "session" middleware will extract the current
session and add it to the incoming request, but sometimes you may need to
access a different session somewhere.
async someMethod() {
let sessionId = '12345';
let sess = await App.$middleware.getSession(sessionId);
}
The "middleware" service automatically includes the following named middleware (listed in a sane order):
express.json()
, for parsing incoming JSON.express.urlencoded
with extended
set to true, for parsing form data.req.session
.The "middleware" service also includes two aliases:
You can define custom middleware and custom middleware aliases by writing a
middleware.js
file in your app. The "middleware" service looks for a map
of middleware names to middleware functions as middleware
and a map of
middleware group aliases to lists of middleware names as aliases
.
Here is an example:
// apps/my_custom_app/middleware.js
function myCustomMiddleware(req, res, next) {
console.log("Custom middleware executed.");
next();
}
module.exports = {
middleware: { myCustomMiddleware },
aliases: {
":custom": ['myCustomMiddleware']
}
};
Under this setup, you could add your custom middleware to a route, along with some included middleware, like this:
router.use(App.$('middleware').middleware(":standard", ":custom"));