mini-express-server
A short implementation of a web server based in express architecture using only build-in node modules
like path, http, and fs
installation
npm i mini-express-server --save
Usage
const { AppServer,ServerError } = require("mini-express-server");
const app = new AppServer()
const port = 1234;
app.use((req, res,next) => {
console.log("Hello world")
req.context["date"] = new Date();
next();
})
app.get(`/api`, (req, res) => {
const { query, params, body, headers, context } = req;
context["server"] = "my-app-server";
res.status(200).json({ query, params, body, headers, context });
})
app.listen(port, () => {
console.log("Server listening: ", port)
})
You can configure your custom Error handler
const { AppServer,ServerError } = require("mini-express-server");
const app = new AppServer()
const port = 1234;
app.use((req, res,next) => {
console.log("Hello world")
req.context["date"] = new Date();
next();
})
app.get(`/api`, (req, res) => {
const { query, params, body, headers, context } = req;
context["server"] = "my-app-server";
res.status(200).json({ query, params, body, headers, context });
})
app.get(`/endpoind`, (req, res, next) => {
next(new ServerError(400,"Custom Error",[{message:"Custom error to test"}]))
})
app.post(`/endpoind/:id`, (req, res) => {
let total = 0;
for(let i=0;i<100;i++){
total+=i;
if(i == 40){
throw new Error("Custom Error also like this")
}
}
res.status(200).json({ id:req.params.id,sum:total });
})
app.setErrorHandler((req, res, error) => {
console.error("THere is an error: ", error);
let code = error.code && !isNaN(parseInt(error.code)) ? error.code : 500;
res.status(code).json({ message: error.message, error: true, meta: error.meta })
})
app.listen(port, () => {
console.log("Server listening: ", port)
})
Stackblitz example
https://stackblitz.com/edit/node-mpg9k4?file=index.js