1.4.6 • Published 4 months ago

rayo v1.4.6

Weekly downloads
33
License
MIT
Repository
github
Last release
4 months ago

Rayo Codacy Badge CodeFactor Coverage Status Vulnerability score Known Vulnerabilities

This is a framework for the modern web; small, slick, elegant and fast. We built Rayo after spending too much time trying to fix the problems we encountered with other frameworks. We needed something that could be an almost out-of-the-box replacement for what most of our systems were built upon, without sacrificing productivity or performance.

Your server will feel like it got hit by a lightning bolt...

In a nutshell

  • Really fast (Like, really fast. See @rayo/benchmarks),
  • similar API to Express¹,
  • compatible with (most) 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. ² Some middleware rely on Express-specific features, which Rayo may or may not implement.

There are examples 🔎 throughout the read.

Install

$> npm i rayo

Use

import rayo from 'rayo';

rayo({ port: 5050 })
  .get('/hello/:user', (req, res) => res.end(`Hello ${req.params.user}`))
  .start();
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.

Note: 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.

Handler signature

/**
 * @param {object}   req
 * @param {object}   res
 * @param {function} [step]
 */
const fn = (req, res, step) => {
  // Your logic.
};

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 your own error function (see onError under options) you may invoke it at any time by calling step() 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.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.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.storm {object}

    • Harness the full power of multi-core CPUs. Rayo will spawn an instance across each core.
    • Accepts the same options object as @rayo/storm. See for @rayo/storm for details.
    • Default: null (no clustering)
  • options.server {http.Server}

  • options.notFound {function}

    Invoked when undefined paths are requested.

    /**
     * @param {object} req
     * @param {object} res
     */
    const fn = (req, res) => {
      // Your logic.
    };

    Default: Rayo will end the response with a "Page not found." message and 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 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 @rayo/compress 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}

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

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.

import rayo from 'rayo';

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

Available modules

Examples

Can be found here.

Contribute

See our contributing notes.

Kindly sponsored by

Acknowledgements

:clap: Thank you to everyone who has made Node.js possible and to all community members actively contributing to it. :steam_locomotive: Most of Rayo was written in chunks of 90 minutes per day and on the train while commuting to work.

License

MIT

1.4.6

4 months ago

1.4.5

7 months ago

1.4.4

7 months ago

1.4.2

7 months ago

1.4.0

1 year ago

1.3.10

2 years ago

1.3.9

2 years ago

1.3.8

2 years ago

1.3.6

3 years ago

1.3.5

4 years ago

1.3.4

4 years ago

1.3.3

5 years ago

1.3.2

5 years ago

1.3.1

5 years ago

1.3.0

5 years ago

1.2.9

5 years ago

1.2.8

5 years ago

1.2.7

5 years ago

1.2.6

5 years ago

1.2.5

6 years ago

1.2.4

6 years ago

1.2.3

6 years ago

1.2.2

6 years ago

1.2.1

6 years ago

1.2.0

6 years ago

1.1.5

6 years ago

1.1.4

6 years ago

1.1.2

6 years ago

1.1.1

6 years ago

1.1.0

6 years ago

1.0.5

6 years ago

1.0.4

6 years ago

1.0.3

6 years ago

1.0.2-RC1

6 years ago

1.0.2

6 years ago

1.0.1

6 years ago

1.0.0

6 years ago

0.5.10

6 years ago

0.5.8

6 years ago

0.5.7

6 years ago

0.5.6

6 years ago

0.5.5

6 years ago

0.5.3

6 years ago

0.5.2

6 years ago

0.5.1

6 years ago

0.5.0

6 years ago