@ev-fns/endpoint
TypeScript icon, indicating that this package has built-in type declarations

1.0.0 • Public • Published

@ev-fns/endpoint

Async request handler for expressjs

  • endpoint endpoint: (handler: express.RequestHandler) => express.RequestHandler

version node downloads dependencies github

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"}

Package Sidebar

Install

npm i @ev-fns/endpoint

Weekly Downloads

7

Version

1.0.0

License

MIT

Unpacked Size

2.68 kB

Total Files

4

Last publish

Collaborators

  • eliseuvideira