Rayo

In a nutshell

  • Really fast (Like really fast. See how it compares),
  • similar API to Express¹,
  • compatible with Express middleware,
  • extensible & plugable,
  • < 85 LOC (with routing and all).
¹ Rayo is not intended to be an Express replacement, thus the API is similar, inspired-by, but not identical.

Install

$> npm i rayo

Use

import rayo from 'rayo';

rayo({ port: 5050 })
  .get('/hello/:user', (req, res) => res.end(`Hello ${req.params.user}`))
  .start();

With multiple handlers

import rayo from 'rayo';

// "age" handler
const age = (req, res, step) => {
  req.age = 21;
  step();
};

// "name" handler
const name = (req, res, step) => {
  req.name = `Super ${req.params.user}`;
  step();
};

rayo({ port: 5050 })
  .get('/hello/:user', age, name, (req, res) => {
    res.end(
      JSON.stringify({
        age: req.age,
        name: req.name
      })
    );
  })
  .start();

A note on handlers

handler functions accept an IncomingMessage (a.k.a req), a ServerResponse (a.k.a res) and a step through (a.k.a step) function. step() is optional and may be used to move the program's execution logic to the next handler in the stack.

step() may also be used to return an error at any time. See error handling.

An error will be thrown if step() is called on an empty stack.

Each handler exposes Node's native ServerResponse (res) object and it's your responsibility to deal with it accordingly, e.g. end the response (res.end()) where expected.

If you need an easier and more convenient way to deal with your responses, take a look at @rayo/send.

Error handling

Please keep in mind that:
"Your code, your errors."¹
- It's your responsibility to deal with them accordingly.

² Rayo is WIP, so you may encounter actual errors that need to be dealt with. If so, please point them out to us via a pull request. 👍

If you have implemented a custom error function (see onError under options) you may invoke it at any time by calling the step() function with an argument.

import rayo from 'rayo';

const options = {
  port: 5050,
  onError: (error, req, res) => {
    res.end(`Here's your error: ${error}`);
  }
};

rayo(options)
  .get('/', (req, res, step) => step('Thunderstruck!'))
  .start();

In the above example, the error will be returned on the / path, since step() is being called with an argument. Run the example, open your browser and go to http://localhost:5050 and you will see "Here's your error: Thunderstruck!".

If you don't have an error function, you may still call step() (with an argument), which will use Rayo's own error function.

API

rayo(options = {})

@param   {object} [options]
@returns {Rayo}
  • options.port {number}

    • Listen on this port for incoming connections.
    • If port is omitted or is 0, the operating system will assign an arbitrary, unused port.
  • options.host {string}

    • Listen on this host for incoming connections.
    • If host is omitted, the server will accept connections on the unspecified IPv6 address (::) when IPv6 is available, or the unspecified IPv4 address (0.0.0.0) otherwise.
  • options.server {http.Server}

  • options.notFound {function}

    Invoked when undefined paths are requested.
    /**
     * @param {object} req
     * @param {object} res
     */
    const fn = (req, res) => {
      // Your custom logic.
    }
    By default, Rayo will send a "Page not found." message with a 404` status code.
  • options.onError {function}

    Invoked when step() is called with an argument.
  • /**
     * @param {*}        error
     * @param {object}   req
     * @param {object}   res
     * @param {function} [step]
     */
    const fn = (error, req, res, step) => {
      // Your custom logic.
    }

.verb(path, …handlers)

@param   {string}   path
@param   {function} handlers - Any number, separated by a comma.
@returns {rayo}
Rayo exposes all HTTP verbs as instance methods.
Requests that match the given verb and path will be routed through the specified handlers.

This method is basically an alias of the .route method, with the difference that the verb is defined by the method name itself.

import rayo from 'rayo';

/**
 * Setup a path ('/') on the specified HTTP verbs.
 */
rayo({ port: 5050 })
  .get('/', (req, res) => res.end('Thunderstruck, GET'))
  .head('/', (req, res) => res.end('Thunderstruck, HEAD'))
  .start();

.all(path, …handlers)

@param   {string}   path
@param   {function} handlers - Any number, comma separated.
@returns {rayo}
Requests which match any verb and the given path will be routed through the specified handlers.
import rayo from 'rayo';

/**
 * Setup a path ('/') on all HTTP verbs.
 */
rayo({ port: 5050 })
  .all('/', (req, res) => res.end('Thunderstruck, all verbs.'))
  .start();

.through(…handlers)

@param   {function} handlers - Any number, comma separated.
@returns {rayo}
All requests, any verb and any path, will be routed through the specified handlers.
import rayo from 'rayo';

// "age" handler
const age = (req, res, step) => {
  req.age = 21;
  step();
};

// "name" handler
const name = (req, res, step) => {
  req.name = 'Rayo';
  step();
};

rayo({ port: 5050 })
  .through(age, name)
  .get('/', (req, res) => res.end(`${req.age} | ${req.name}`))
  .start();

.route(verb, path, …handlers)

@param   {string}   verb
@param   {string}   path
@param   {function} handlers - Any number, comma separated.
@returns {rayo}
Requests which match the given verb and path will be routed through the specified handlers.
import rayo from 'rayo';

rayo({ port: 5050 })
  .route('GET', '/', (req, res) => res.end('Thunderstruck, GET'))
  .start();

.bridge(path)

@param   {string} path - The URL path to which verbs should be mapped.
@returns {bridge}
Route one path through multiple verbs and handlers.

A bridge instance exposes all of Rayo's routing methods (.through, .route, .verb and .all). You may create any number of bridges and Rayo will automagically take care of mapping them.

What makes bridges really awesome is the fact that they allow very granular control over what your application exposes. For example, enabling content compression only on certain paths.

import rayo from 'rayo';

const server = rayo({ port: 5050 });

/**
 * Bridge the `/home` path to the `GET` and `HEAD` verbs.
 */
server
  .bridge('/home')
  .get((req, res) => res.end('You are home, GET'))
  .head((req, res) => res.end('You are home, HEAD'));

/**
 * Bridge the `/game` path to the `POST` and `PUT` verbs.
 */
server
  .bridge('/game')
  .post((req, res) => res.end('You are at the game, POST'))
  .put((req, res) => res.end('You are at the game, PUT'));

const auth = (req, res, step) => {
  req.isAuthenticated = true;
  step();
};

const session = (req, res, step) => {
  req.hasSession = true;
  step();
};

/**
 * Bridge the `/account` path to the `GET`, `POST` and `PUT` verbs
 * and through two handlers.
 */
server
  .bridge('/account')
  .through(auth, session)
  .get((req, res) => res.end('You are at the account, GET'))
  .post((req, res) => res.end('You are at the account, POST'))
  .put((req, res) => res.end('You are at the account, PUT'));

server.start();

.start(callback)

@param   {function} [callback] - Invoked on the server's `listening` event.
@returns {http.Server}

Rayo will return the server address with the callback, if one was provided. This is useful, for example, to get the server port in case no port was specified in the options.

Starts Rayo -Your server is now listening for incoming requests.

import rayo from 'rayo';

rayo({ port: 5050 });
  .get((req, res) => res.end('Thunderstruck'))
  .start((address) => {
    console.log(`Rayo is up on port ${address.port}`);
  });

How does it compare?

Visit the repository for the latest results.

Run on your own hardware; clone this repository, install the dependencies and run npm run bench. Optionally, you may also define your test's parameters:

$> npm run bench -- -u http://localhost:5050 -c 1000 -p 25 -d 10
  • -u url -Default: http://localhost:5050
  • -c connections -Default: 100
  • -p pipelines -Default: 10
  • -d duration -Default: 10 (seconds)
  • -o only Run only one particular benchmark. -Defaults to null.
These results may will vary on different hardware.

Examples

Can be found here.

Contribute

See our contributing notes.

Acknowledgements

👏🏼 Thank you to everyone who has made Node.js possible and to all community members actively contributing to it.

🚂 Most of Rayo was written in chunks of 90 minutes per day and on the train while commuting to work.

License

MIT