@ev-fns/endpoint
v1.0.0
Published
> Async request handler for expressjs
Downloads
10
Maintainers
Readme
@ev-fns/endpoint
Async request handler for expressjs
- endpoint
endpoint: (handler: express.RequestHandler) => express.RequestHandler
Install
yarn add express @ev-fns/endpoint
Usage
const express = require("express");
const { endpoint } = require("@ev-fns/endpoint");
const app = express();
app.use(express.json());
const booksPostOneHandler = endpoint(async (req, res) => {
const { title } = req.body;
if (!title) {
// you can safely throw errors
const err = new Error("title is required");
err.status = 400;
throw err;
}
res.status(201).json({ title });
});
app.post("/books", booksPostOneHandler);
app.use((err, req, res, next) => {
res.status(err.status || 500).json({ message: err.message });
});
app.listen(3000, () => {
console.log("listening at http://localhost:3000");
});
Try it out
$ node index.js
$ curl -i -X POST http://localhost:3000/books
HTTP/1.1 400
...
{"message":"title is required"}
$ curl -i -X POST -H "Content-Type: application/json" -d '{"title":"The C Programming Language"}' http://localhost:3000/books
HTTP/1.1 201
...
{"title":"The C Programming Language"}