@ev-fns/endpoint

Async request handler for expressjs

Usage no npm install needed!

<script type="module">
  import evFnsEndpoint from 'https://cdn.skypack.dev/@ev-fns/endpoint';
</script>

README

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