Express Resource Router Middleware

0.7.0 · abandoned · verified Wed Apr 22

resource-router-middleware provides a concise, declarative way to define RESTful API endpoints for Express applications. It allows developers to configure a full CRUD (Create, Read, Update, Delete) resource using a single object literal, mapping HTTP methods (GET, POST, PUT, DELETE) to corresponding handler functions (list, create, read, update, delete). The current stable version is 0.7.0, released in 2017. The project appears to be unmaintained, with its last commit in 2020, suggesting an abandoned release cadence. Its key differentiator is simplifying the definition of standard REST resources, abstracting away individual route declarations and integrating with Express's parameter loading mechanisms, which can lead to more readable and organized route definitions compared to manual `app.get()`, `app.post()` etc.

Common errors

Warnings

Install

Imports

Quickstart

This example sets up an Express application with a `/users` RESTful resource using `resource-router-middleware`. It demonstrates defining all CRUD operations for a 'user' entity, including data loading and error handling. It shows how to use `express.json()` for request body parsing and how to start the server.

import express from 'express';
import resource from 'resource-router-middleware';

const app = express();
app.use(express.json()); // For parsing application/json

const users = [];

// A simple mock for `users` data
for (let i = 0; i < 3; i++) {
  users.push({ id: String(i), name: `User ${i}`, email: `user${i}@example.com` });
}

app.use('/users', resource({
  mergeParams: true,
  id: 'user',

  load(req, id, callback) {
    const user = users.find(u => u.id === id);
    const err = user ? null : 'Not found';
    callback(err, user);
  },

  list({ params }, res) {
    res.json(users);
  },

  create({ body }, res) {
    const newUser = { ...body, id: String(users.length) };
    users.push(newUser);
    res.status(201).json(newUser);
  },

  read({ user }, res) {
    res.json(user);
  },

  update({ user, body }, res) {
    const index = users.indexOf(user);
    if (index !== -1) {
      for (let key in body) {
        if (key !== 'id') {
          user[key] = body[key];
        }
      }
      users[index] = user;
      res.status(204).send();
    } else {
      res.status(404).send('Not Found');
    }
  },

  delete({ user }, res) {
    const index = users.indexOf(user);
    if (index !== -1) {
      users.splice(index, 1);
      res.status(204).send();
    } else {
      res.status(404).send('Not Found');
    }
  }
}));

app.get('/', (req, res) => res.send('Welcome to the API! Try /users or /users/0'));

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server running on http://localhost:${PORT}`);
  console.log('Available endpoints: /users (GET, POST), /users/:id (GET, PUT, DELETE)');
});

view raw JSON →