npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

exprestive

v1.3.0

Published

Expressive RESTful express router

Downloads

104

Readme

expRESTive

NPM Version Build Status Dependency Status

Add rails-style routes and controllers to Express.js (and other connect-based web frameworks).

Basic usage

Assuming you have already created an Express application by following the Express installation instructions. Now:

  • add expRESTive to your package.json file: $ npm install --save exprestive

  • add the expRESTive middleware to your application

    const express = require('express');
    const exprestive = require('exprestive');
    
    app = express();
    app.use(exprestive());
    
    app.listen(3000);
  • create a routes.js file in the same directory as your server

    // routes.js
    module.exports = ({ GET, POST, PUT, DELETE }) => {
      GET('/hello', { to: 'helloWorld#index' });
    };
  • create a controllers/ directory in the same directory as your server and populate it with controllers. Controller file names must end in controller (with a js or compile-to-js extension). This restriction can be changed with the controllersPattern option. See options.

    // controllers/hello_world_controller.js
    module.exports = class HelloWorldController {
      index(req, res) {
        res.end('hello world');
      }
    };
  • visit localhost:3000/hello in your browser

Reverse routing

Exprestive exports url building functions to this.routes in controllers and res.locals.routes for each request.

Saving / accessing reverse routes

In your routes file you can pass an as parameter to non-restful routes to define a reverse route.

// routes.js
module.exports = ({ GET }) => {
  GET('/foo/bar', { to: 'foo#bar', as: 'foobar' });
};

In a controller you can access this path with this.routes.foobar()

// controllers/foo_controller.js
module.exports = class FooController {
  bar(req, res) {
    this.routes.foobar(); // returns {path: "/foo/bar", method: "GET"}
  }
};

In a view you can access this path with routes.foobar()

//- index.jade
a(href=routes.foobar()) Visit foobar

Parameters

If a route has parameters, the reverse route can take the parameters in order as arguments or as an object

// routes.js
module.exports = ({ GET }) => {
  GET('/users/:userId/posts/:id', { to: 'posts#show', as: 'userPost' });
};

// controllers/posts_controller.js
class PostsController {
  show(req, res) {
    this.routes.userPost(1, 2).path;               // returns "/users/1/posts/2"
    this.routes.userPost({userId: 1, id: 2}).path; // returns "/users/1/posts/2"
  }
};

Restful routing

The resources helper can be used to build all the standard RESTFUL routes

// routes.js
module.exports = ({resources}) => {
  resources('users');
};

is equivalent to

// routes.js
module.exports = ({ DELETE, GET, POST, PUT }) => {
  GET(    '/users',          { to: 'user#index',   as: 'users'       });
  GET(    '/users/new',      { to: 'user#new',     as: 'newUser'     });
  GET(    '/users/:id',      { to: 'user#show',    as: 'user'        });
  GET(    '/users/:id/edit', { to: 'user#edit',    as: 'editUser'    });
  PUT(    '/users/:id',      { to: 'user#update',  as: 'updateUser'  });
  POST(   '/users',          { to: 'user#create',  as: 'createUser'  });
  DELETE( '/users/:id',      { to: 'user#destroy', as: 'destroyUser' });
};

You can limit the restful routing with the options except: or only:

// routes.js
module.exports = ({resources}) => {
  resources('users', {only: ['index', 'new', 'create', 'destroy']});
  resources('posts', {except: ['index']});
};

Scoped routing

The scope helper can be used to create a prefixed set of routes:

// routes.js
module.exports = ({ GET, scope }) => {
  scope('/api', () => {
    GET('/users', {to: 'users#index'});
    GET('/widgets', {to: 'widgets#index'});
  });
};

This is equivalent to:

// routes.js
module.exports = ({ GET }) => {
  GET('/api/users', { to: 'users#index' });
  GET('/api/widgets', { to: 'widgets#index' });
};

Scopes can also be nested:

// routes.js
module.exports = ({ GET, resources, scope }) => {
  scope('/api', () => {
    scope('/v1', () => {
      resources('users');
      GET('/widgets', { to: 'widgets#index' });
    });
  });
};

Middleware Support

Adding per-route middleware can be done in the controller by setting middleware.

// controllers/hello_world_controller.js
const someMiddleware = require('some-middleware');

module.exports = class HelloWorldController {
  constructor() {
    this.middleware = { index: someMiddleware };
  }

  index(req, res) {
    res.end('hello world');
  }
};

The specified middleware will be inserted in the chain before the controller action. An array of middleware can also be specified and they will be inserted in the chain in the specified order.

BaseController

A base controller has been exposed that application controllers can optionally extend. The base controller exposes several helper methods.

The useMiddleware helper adds middleware declartions for all controller actions. An array of middleware can also be specified and they will be inserted in the chain in the specified order. Often this would be used in the constructor of a controller. The function also accepts options of only or except which modify the list of actions.

// controllers/hello_world_controller.js
const BaseController = require('exprestive').BaseController;
const someMiddleware = require('some-middleware');
const someOtherMiddleware = require('some-other-middleware');

module.exports = class HelloWorldController extends BaseController {
  constructor() {
    super();
    this.useMiddleware(someMiddleware);
    this.useMiddleware(someOtherMiddleware, {only: 'index'});
  }

  index(req, res) {
    res.end('hello world index');
  }

  show(req, res) {
    res.end('hello world show');
  }
};

The getActions helper returns an array of all the actions on the controller. It also takes options of only or except to modify the list.

Options

Options are provided to the exprestive function.

app = express();
app.use(exprestive({ appDir: './www' }));
  • appDir
    • Directory used as a base directory for routes file and controllers directory
    • default: __dirname of the file that calls exprestive()
  • controllersPattern
    • Glob pattern used to find controllers. Resolved relative to appDir
    • default: 'controllers/*controller.+([^.])'
  • dependencies
    • Object passed to controller constructors
    • default: {}
  • routesFilePath
    • Path to routes file. Resolved relative to appDir. This is passed to require, so extension is optional
    • default: 'routes'

Development

See the developer documentation