@microbackend/plugin-express
v1.0.1
Published
Micro-backend express.js plugin
Downloads
5
Readme
@microbackend/plugin-express
Microbackend plugin for express.js.
Installation
This plugin is automatically included if you had initialized a microbackend project with:
npx microbackend init --template express
To install it as a standalone dependency:
npx microbackend plugin add @microbackend/plugin-express
Usage
For illustration purposes, create the following files in your project:
src/extension/express/route/route1.ts
:
import { IMicrobackendInitFunction } from "@microbackend/plugin-express";
export default ((): IMicrobackendRouteCreator => {
return () => {
return {
handler: async (_req, res) => {
res.json({ value: 1 });
},
method: "get",
route: "/route1",
};
};
})();
src/extension/express/route/middleware1.ts
:
import { IMicrobackendMiddlewareCreator } from "@microbackend/plugin-express";
export default ((): IMicrobackendMiddlewareCreator => {
return () => {
return {
handler: (req, _res, next) => {
console.log(req);
next();
},
};
};
})();
Then, in your main application entry file:
import { createExpressApplication } from "@microbackend/plugin-express";
import express from "express";
export default createExpressApplication().then((app) => {
app.use(((err, _req, res, _next) => {
res.status(err.status || 500).json({ error: err.message });
}) as express.ErrorRequestHandler);
const port = process.env["PORT"] || 3001;
app.listen(port, () => {
console.log("Started example server on port", port);
});
});
Now, your Express app will automatically have a middleware that logs all requests,
and a request handler registered for route /route1
.
In short, the extension patterns supported by this plugin are:
IMicrobackendRouteCreator
, supported byextension/express/route
: A function type that creates an Express route. Thehandler
option can either be a function or anexpress.Router
instance.IMicrobackendMiddlewareCreator
, supported byextension/express/middleware
: A function type that creates an Express middleware.
For more information on extension patterns, please have a look at
@microbackend/plugin-core
.