UNPKG

43.3 kBMarkdownView Raw
1# Ravel
2> Forge past a tangle of modules. Make a cool app.
3
4[![GitHub license](https://img.shields.io/badge/license-MIT-blue.svg)](https://raw.githubusercontent.com/raveljs/ravel/master/LICENSE) [![npm version](https://badge.fury.io/js/ravel.svg)](http://badge.fury.io/js/ravel) [![Dependency Status](https://david-dm.org/raveljs/ravel.svg)](https://david-dm.org/raveljs/ravel) [![npm](https://img.shields.io/npm/dm/ravel.svg?maxAge=2592000)](https://www.npmjs.com/package/ravel) [![Build Status](https://travis-ci.org/raveljs/ravel.svg?branch=master)](https://travis-ci.org/raveljs/ravel) [![Build status](https://ci.appveyor.com/api/projects/status/5kx5j2d1fhyn9yn3/branch/master?svg=true)](https://ci.appveyor.com/project/Ghnuberath/ravel/branch/master) [![Code Climate](https://codeclimate.com/github/raveljs/ravel/badges/gpa.svg)](https://codeclimate.com/github/raveljs/ravel) [![Test Coverage](https://codeclimate.com/github/raveljs/ravel/badges/coverage.svg)](https://codeclimate.com/github/raveljs/ravel/coverage) [![js-semistandard-style](https://img.shields.io/badge/code%20style-semistandard-brightgreen.svg?style=flat-square)](https://github.com/Flet/semistandard)
5
6Ravel is a tiny, sometimes-opinionated foundation for creating organized, maintainable, and scalable web applications in [node.js](https://github.com/joyent/node) with [ES2016/2017](http://kangax.github.io/compat-table/esnext/).
7
8**Note:** The `master` branch may be in an unstable or even broken state during development. Please use [releases](https://github.com/raveljs/ravel/releases) instead of the `master` branch to view stable code.
9
10## Table of Contents
11
12<!-- TOC depthFrom:2 depthTo:3 withLinks:1 updateOnSave:1 orderedList:0 -->
13
14- [Table of Contents](#table-of-contents)
15- [Introduction](#introduction)
16- [Installation](#installation)
17- [Architecture](#architecture)
18 - [Modules (and Errors)](#modules-and-errors)
19 - [Routes](#routes)
20 - [Resources](#resources)
21 - [Bringing it all together](#bringing-it-all-together)
22 - [Decorator Transpilation](#decorator-transpilation)
23 - [Running the Application](#running-the-application)
24- [API Documentation](#api-documentation)
25 - [Ravel App](#ravel-app)
26 - [Managed Configuration System](#managed-configuration-system)
27 - [Ravel.Error](#ravelerror)
28 - [Ravel.Module](#ravelmodule)
29 - [Ravel.Routes](#ravelroutes)
30 - [Ravel.Resource](#ravelresource)
31 - [Response Caching](#response-caching)
32 - [Database Providers](#database-providers)
33 - [Transaction-per-request](#transaction-per-request)
34 - [Scoped Transactions](#scoped-transactions)
35 - [Authentication Providers](#authentication-providers)
36 - [Authentication](#authentication)
37- [Deployment and Scaling](#deployment-and-scaling)
38
39<!-- /TOC -->
40
41## Introduction
42
43Ravel is inspired by the simplicity of [koa](http://koajs.com/) and [express](http://expressjs.com), but aims to provide a pre-baked, well-tested and highly modular solution for creating enterprise web applications by providing:
44
45- A standard set of well-defined architectural components so that your code stays **organized**
46- Rapid **REST API** definition
47- Easy **bootstrapping** via an enforced, reference configuration of [koa](http://koajs.com/) with critical middleware
48- Dependency injection (instead of relative `require`s)
49
50And a few other features, plucked from popular back-end frameworks:
51
52- Transaction-per-request
53- Simple authentication and authentication configuration (no complex [passport](https://github.com/jaredhanson/passport) setup)
54- Externalized session storage for horizontal scalability
55
56Ravel is layered on top of awesome technologies, including:
57- [koa](http://koajs.com/)
58- [Passport](https://github.com/jaredhanson/passport)
59- [Intel](https://github.com/seanmonstar/intel)
60- [Redis](https://github.com/antirez/redis)
61- [docker](http://docker.com)
62
63
64## Installation
65
66> As Ravel uses async/await and several other ES2015/2016 features, you will need to use a 7.6.x+ distribution of node
67
68```bash
69$ npm install ravel
70```
71
72Ravel also relies on [Redis](https://github.com/antirez/redis). If you don't have it installed and running, try using [docker](docker.com) to quickly spin one up:
73
74```bash
75$ docker run -d -p 6379:6379 redis
76```
77
78## Architecture
79
80Ravel applications consist of a few basic parts:
81
82- **Modules:** plain old classes which offer a great place to write modular application logic, middleware, authentication logic, etc.
83- **Routes:** a low-level place for general routing logic
84- **Resources:** built on top of `Routes`, `Resource`s are REST-focused
85- **Errors:** Node.js `Error`s which are associated with an HTTP response code. `throw` them or `reject` with them and `Routes` and `Resource`s will respond accordingly
86
87If you're doing it right, your applications will consist largely of `Module`s, with a thin layer of `Routes` and `Resource`s on top.
88
89### Modules (and Errors)
90
91`Module`s are plain old node.js modules exporting a single class which encapsulates application logic. `Module`s support dependency injection of core Ravel services and other Modules alongside npm dependencies *(no relative `require`'s!)*. `Module`s are instantiated safely in dependency-order, and cyclical dependencies are detected automatically.
92
93For more information about `Module`s, look at [Ravel.Module](#ravelmodule) below.
94
95*modules/cities.js*
96```javascript
97const Ravel = require('ravel');
98const Error = Ravel.Error;
99const Module = Ravel.Module;
100const inject = Ravel.inject;
101
102/**
103 * First, we'll define an Error we will throw when a requested
104 * city is not found. This Error will be associated with the
105 * HTTP error code 404.
106 */
107class MissingCityError extends Error {
108 constructor (name) {
109 super(`City ${name} does not exist.`, Ravel.httpCodes.NOT_FOUND);
110 }
111}
112
113/**
114 * Our main Module, defining logic for working with Cities
115 */
116@inject('moment')
117class Cities extends Module {
118 constructor (moment) {
119 super();
120 this.moment = moment;
121 this.cities = ['Toronto', 'New York', 'Chicago']; // our fake 'database'
122 }
123
124 getAllCities () {
125 return Promise.resolve(this.cities);
126 }
127
128 getCity (name) {
129 return new Promise((resolve, reject) => {
130 const index = this.cities.indexOf(name);
131 if (index !== -1) {
132 resolve(this.cities[index]);
133 } else {
134 // Ravel will automatically respond with the appropriate HTTP status code!
135 this.log.warn(`User requested unknown city ${name}`);
136 reject(new MissingCityError(name));
137 }
138 });
139 }
140}
141
142// Export Module class
143module.exports = Cities;
144```
145
146### Routes
147
148`Routes` are `Ravel`'s lower-level wrapper for `koa` (`Resource`s are the higher-level one). They support GET, POST, PUT and DELETE requests, and middleware, via decorators. Like `Module`s, they also support dependency injection. Though `Routes` can do everything `Resources` can do, they are most useful for implementing non-REST things, such as static content serving or template serving (EJS, Jade, etc.). If you want to build a REST API, use `Resource`s instead (they're up next!).
149
150For more information about `Routes`, look at [Ravel.Routes](#ravelroutes) below.
151
152*routes/index.js*
153```javascript
154const Ravel = require('ravel');
155const Routes = Ravel.Routes;
156const inject = Ravel.inject;
157const before = Routes.before; // decorator to add middleware to an endpoint within the Routes
158const mapping = Routes.mapping; // decorator to associate a handler method with an endpoint
159
160@inject('middleware1') // middleware from NPM, or your own modules, etc.
161class ExampleRoutes extends Routes {
162 constructor (middleware1) {
163 super('/'); // base path for all routes in this class. Will be prepended to the @mapping.
164 this.middleware1 = middleware1;
165 // you can also build middleware right here!
166 this.middleware2 = async function (next) {
167 await next;
168 };
169 }
170
171 // bind this method to an endpoint and verb with @mapping. This one will become GET /app
172 @mapping(Routes.GET, 'app')
173 @before('middleware1','middleware2') // use @before to place middleware before appHandler
174 async appHandler (ctx) {
175 // ctx is just a koa context! Have a look at the koa docs to see what methods and properties are available.
176 ctx.body = '<!DOCTYPE html><html><body>Hello World!</body></html>';
177 ctx.status = 200;
178 }
179}
180
181// Export Routes class
182module.exports = ExampleRoutes;
183```
184
185### Resources
186
187What might be referred to as a *controller* in other frameworks, a `Resource` module defines HTTP methods on an endpoint, supporting the session-per-request transaction pattern via Ravel middleware. `Resource`s also support dependency injection, allowing for the easy creation of RESTful interfaces to your `Module`-based application logic. Resources are really just a thin wrapper around `Routes`, using specially-named handler functions (`get`, `getAll`, `post`, `put`, `putAll`, `delete`, `deleteAll`) instead of `@mapping`. This convention-over-configuration approach makes it easier to write proper REST APIs with less code, and is recommended over "carefully chosen" `@mapping`s in a `Routes` class.
188
189For more information about `Resource`s, look at [Ravel.Resource](#ravelresouce) below.
190
191*resources/city.js*
192```javascript
193// Resources support dependency injection too!
194// Notice that we have injected our cities Module by name.
195const Ravel = require('ravel');
196const Resource = Ravel.Resource;
197const inject = Ravel.inject;
198const before = Resource.before; // decorator to add middleware to an endpoint within the Resource
199
200// using @before at the class level decorates all endpoint methods with middleware
201@inject('cities')
202class CitiesResource extends Resource {
203 constructor (cities) {
204 super('/cities'); //base path
205 this.cities = cities;
206
207 // some other middleware, which you might have injected from a Module or created here
208 this.anotherMiddleware = async function (next) {
209 await next;
210 };
211 }
212
213 // no need to use @mapping here. Routes methods are automatically mapped using their names.
214 async getAll (ctx) { // just like in Routes, ctx is a koa context.
215 ctx.body = await this.cities.getAllCities();
216 }
217
218 @before('anotherMiddleware') // using @before at the method level decorates this method with middleware
219 async get (ctx) { // get routes automatically receive an endpoint of /cities/:id (in this case).
220 ctx.body = await this.cities.getCity(ctx.params.id);
221 }
222
223 // post, put, putAll, delete and deleteAll are
224 // also supported. Not specifying them for
225 // this resource will result in calls using
226 // those verbs returning HTTP 501 NOT IMPLEMENTED
227
228 // postAll is not supported, because it makes no sense
229}
230
231// Export Resource class
232module.exports = CitiesResource;
233```
234
235### Bringing it all together
236
237*app.js*
238```javascript
239const app = new require('ravel')();
240
241// parameters like this can be supplied via a .ravelrc.json file
242app.set('keygrip keys', ['mysecret']);
243
244app.modules('./modules'); //import all Modules from a directory
245app.resources('./resources'); //import all Resources from a directory
246app.routes('./routes/index.js'); //import all Routes from a file
247
248// start it up!
249app.start();
250```
251
252### Decorator Transpilation
253
254Since decorators are not yet available in Node, you will need to use a transpiler to convert them into ES2016-compliant code. We have chosen [Babel](https://babeljs.io/) as our recommended transpiler.
255
256```bash
257$ npm install gulp-sourcemaps@1.6.0 babel-core@6.18.2 babel-plugin-transform-decorators-legacy@1.3.4 gulp-babel@6.1.2
258# Note, please add babel-plugin-transform-async-to-generator@6.16.0 if you are using Node v6 instead of v7.
259```
260
261*gulpfile.js*
262```js
263const babelConfig = {
264 'retainLines': true,
265 'plugins': ['transform-decorators-legacy'] // add 'transform-async-to-generator' if you are using Node v6 instead of v7
266};
267gulp.task('transpile', function () {
268 return gulp.src('src/**/*.js') // point it at your source directory, containing Modules, Resources and Routes
269 .pipe(plugins.sourcemaps.init())
270 .pipe(plugins.babel(babelConfig))
271 .pipe(plugins.sourcemaps.write('.'))
272 .pipe(gulp.dest('dist')); // your transpiled Ravel app will appear here!
273});
274```
275
276Check out the [starter project](https://github.com/raveljs/ravel-github-mariadb-starter) to see a working example of this build process.
277
278### Running the Application
279
280```bash
281$ node dist/app.js
282```
283
284## API Documentation
285> [<small>View API docs &#128366;</small>](http://raveljs.github.io/docs/latest/)
286
287### Ravel App
288> [<small>View API docs &#128366;</small>](http://raveljs.github.io/docs/latest/ravel.js.html)
289
290A Ravel application is a root application file (such as `app.js`), coupled with a collection of files exporting `Module`s, `Resource`s and `Routes` (see [Architecture](#architecture) for more information). Getting started is usually as simple as creating `app.js`:
291
292*app.js*
293```js
294const Ravel = require('ravel');
295const app = new Ravel();
296
297// you'll register managed parameters, and connect Modules, Resources and Routes here
298
299app.init();
300
301// you'll set managed parameters here
302
303app.listen();
304```
305
306### Managed Configuration System
307> [<small>View API docs &#128366;</small>](http://raveljs.github.io/docs/latest/core/params.js.html)
308
309Traditional `node` appliations often rely on `process.env` for configuration. This can lead to headaches when an expected value is not declared in the environment, a value is supplied but doesn't match any expected ones, or the name of an environment variable changes and refactoring mistakes are made. To help mitigate this common issue, Ravel features a simple configuration system which relies on three methods:
310
311#### app.registerParameter
312> [<small>View API docs &#128366;</small>](http://raveljs.github.io/docs/latest/core/params.js.html#registerParameter)
313
314Create managed parameters with `app.registerParameter()`:
315
316*app.js*
317```js
318const Ravel = require('ravel');
319const app = new Ravel();
320
321// register a new optional parameter
322app.registerParameter('my optional parameter');
323// register a new required parameter
324app.registerParameter('my required parameter', true);
325// register a required parameter with a default value
326app.registerParameter('my third parameter', true, 'some value');
327
328app.init();
329app.listen();
330```
331
332Many Ravel plugin libraries will automatically create parameters which you will have to supply values for. These parameters will be documented in their `README.md`.
333
334#### app.set
335> [<small>View API docs &#128366;</small>](http://raveljs.github.io/docs/latest/core/params.js.html#set)
336
337Provide values via `app.set()`. Setting an unknown parameter will result in an `Error`.
338
339*app.js*
340```js
341const Ravel = require('ravel');
342const app = new Ravel();
343
344// register a new optional parameter
345app.registerParameter('my optional parameter');
346
347app.init();
348
349// set a value
350app.set('my optional parameter', 'some value');
351// this won't work:
352app.set('an unknown parameter', 'some value');
353
354app.listen();
355```
356
357#### app.get
358> [<small>View API docs &#128366;</small>](http://raveljs.github.io/docs/latest/core/params.js.html#get)
359
360Retrieve values via `app.get()`. Retrieving an unknown parameter will result in an `Error`.
361
362*app.js*
363```js
364const Ravel = require('ravel');
365const app = new Ravel();
366
367// register a new parameter
368app.registerParameter('my required parameter', true, 'default value');
369
370app.init();
371
372// set a value
373app.set('my required parameter', 'some value');
374// get a value
375app.get('my required parameter') === 'some value';
376// this won't work:
377// app.get('an unknown parameter');
378
379app.listen();
380```
381
382#### Core parameters
383
384Ravel has several core parameters:
385
386```js
387// you have to set these:
388app.set('keygrip keys', ['my super secret key']);
389
390// these are optional (default values are shown):
391app.set('redis host', '0.0.0.0');
392app.set('redis port', 6379);
393app.set('redis password', undefined);
394app.set('redis max retries', 10); // connection retries
395app.set('port', 8080); // port the app will run on
396app.set('session key', 'koa.sid'); // the cookie name to use for sessions
397app.set('session max age', null); // session maxAge (default never expires)
398app.set('app route', '/'); // if you have a UI, this is the path users will be sent to when they are logged in
399app.set('login route', '/login'); // if users aren't logged in and you redirect them, this is where they'll be sent
400app.set('koa public directory', undefined); // if you want to statically serve a directory
401app.set('koa view directory', undefined); // for templated views (EJS, Pug, etc.)
402app.set('koa view engine', undefined); // for templated views (EJS, Pug, etc.)
403app.set('koa favicon path', undefined); // favicon middleware configuration
404```
405
406#### .ravelrc.json
407
408To make it easier to supply configuration values to Ravel, a `.ravelrc.json` file can be placed beside `app.js` (or in any parent directory of `app.js`). This is the recommended method of setting parameters, with the exception of ones derived from `process.env` (which would need to be set programmatically).
409
410*.ravelrc.json*
411```
412{
413 "keygrip keys": ["my super secret key"]
414}
415```
416
417### Ravel.Error
418> [<small>View API docs &#128366;</small>](http://raveljs.github.io/docs/latest/util/application_error.js.html)
419
420This is the base `Error` type for Ravel, meant to be extended into semantic errors which can be used within your applications. When you create a custom `Ravel.Error`, you **must** provide an associated HTTP status code, which Ravel will automatically respond with if an HTTP request results in that particular `Error` being thrown. This helps create meaningful status codes for your REST APIs while working within traditional `node` error-handling paradigms (`throw/try/catch` and `Promise.reject()`). Errors are generally best-declared within `Module`, `Resource` or `Routes` files (and not exported), closest to where they are used.
421
422*at the top of some `Module`, `Resource` or `Routes` file (we'll get to this next)*
423```js
424const Ravel = require('ravel');
425/**
426 * Thrown when a user tries to POST something unexpected to /upload
427 */
428class UploadError extends Ravel.Error {
429 constructor (msg) {
430 super(msg, Ravel.httpCodes.BAD_REQUEST);
431 }
432}
433```
434
435### Ravel.Module
436> [<small>View API docs &#128366;</small>](http://raveljs.github.io/docs/latest/core/module.js.html)
437
438`Module`s are meant to contain the bulk of your application logic, either to support endpoints defined in `Resource`s and `Routes`, or to perform tasks at specific points during the Ravel lifecycle (see [Lifecycle Decorators](#lifecycle-decorators) below).
439
440Here's a simple module:
441
442*modules/my-module.js*
443```js
444const Ravel = require('ravel');
445const inject = Ravel.inject; // Ravel's dependency injection decorator
446const Module = Ravel.Module; // base class for Ravel Modules
447
448// inject a custom ravel Module (or your plain classes) beside npm dependencies!
449@inject('path', 'fs', 'custom-module', 'plain-class')
450class MyModule extends Module {
451 constructor (path, fs, custom, plain) { // @inject'd modules are available here as parameters
452 super();
453 this.path = path;
454 this.fs = fs;
455 this.custom = custom;
456 this.plain = plain;
457 }
458
459 // implement any methods you like :)
460 aMethod () {
461 // ...
462 }
463
464 async anAsyncMethod () {
465 // ...
466 }
467}
468
469module.exports = MyModule; // you must export your Module so that Ravel can require() it.
470```
471
472#### Dependency Injection and Module Registration
473> [<small>View API docs &#128366;</small>](http://raveljs.github.io/docs/latest/core/decorators/inject.js.html)
474
475Ravel's *dependency injection* system is meant to address several issues with traditional `require()`s:
476
477- Using `require()` with one's own modules in a complex project often results in statements like this: `require('../../../../my/module');`. This issue is especially pronounced when `require()`ing source modules in test files.
478- Cyclical dependencies between modules are not always obvious in a large codebase, and can result in unexpected behaviour.
479
480Ravel addresses this with the the [`@inject`](http://raveljs.github.io/docs/latest/core/decorators/inject.js.html) decorator:
481
482*modules/my-module.js*
483```js
484const Ravel = require('ravel');
485const inject = Ravel.inject;
486const Module = Ravel.Module;
487
488@inject('another-module') // inject another Module from your project without require()!
489class MyModule extends Module {
490 constructor (another) { // @inject'd modules are available here as parameters
491 super();
492 this.another = another;
493 }
494}
495module.exports = MyModule;
496```
497
498The injection name of `another-module` comes from its filename, and can be overriden in `app.js`:
499
500*app.js*
501```js
502// ...
503const app = new Ravel();
504// the first argument is the path to the module file.
505// the second is the name you assign for dependency injection.
506app.module('./modules/my-module', 'my-module');
507app.module('./modules/another-module', 'another-module');
508// assigning names manually becomes tedious fast, so Ravel can
509// infer the names from the names of your files when you use
510// app.modules to scan a directory:
511app.modules('./modules'); // this would register modules with the same names as above
512```
513
514`Module`s are singletons which are instantiated in *dependency-order* (i.e. if `A` depends on `B`, `B` is guaranteed to be constructed first). Cyclical dependencies are detected automatically and result in an `Error`.
515
516`app.module`, `app.modules` and `@inject` also work on files exporting plain classes which do not extend `Ravel.Module`. This makes it easier to create and/or use simple, plain classes which do not need access to the full Ravel framework (i.e. `this.log`, `this.ApplicationError`, etc.).
517
518To further simplify working with imports in Ravel, you can `@inject` core `node` modules and `npm` dependencies (installed in your local `node_modules` or globally) alongside your own `Module`s:
519
520```js
521const Ravel = require('ravel');
522const inject = Ravel.inject;
523const Module = Ravel.Module;
524
525@inject('another-module', 'path', 'moment') // anything that can be require()d can be @injected
526class MyModule extends Module {
527 constructor (another, path, moment) {
528 super();
529 // ...
530 }
531}
532module.exports = MyModule;
533```
534
535#### Module Namespacing
536
537In a large project, it may become desirable to namespace your `Module`s to avoid naming conflicts. This is easily accomplished with Ravel by separating source files for `Module`s into different directories. Let's assume the following project structure:
538
539```
540app.js
541.ravelrc.json
542modules/
543 core/
544 my-module.js
545 util/
546 my-module.js
547```
548
549Then, import the `Module` directory as before, using `app.modules()`:
550
551*app.js*
552```js
553// ...
554const app = new Ravel();
555app.modules('./modules');
556// core/my-module can now be injected using @inject(core.my-module)!
557// util/my-module can now be injected using @inject(util.my-module)!
558```
559
560> Essentially, Ravel ignores the path you pass to `app.modules()` and uses any remaining path components to namespace `Module`s.
561
562#### Lifecycle Decorators
563> [<small>View API docs &#128366;</small>](http://raveljs.github.io/docs/latest/core/decorators/lifecycle.js.html)
564
565`Module`s are also a great place to define logic which should run at particular points during the Ravel lifecycle. Decorating a `Module` method appropriately results in that method firing exactly once at the specified time:
566
567```js
568const Ravel = require('ravel');
569const Module = Ravel.Module;
570const prelisten = Module.prelisten;
571
572class MyInitModule extends Module {
573 // ...
574 @prelisten
575 initDBTables () {
576 // ...
577 }
578}
579module.exports = MyInitModule;
580```
581
582There are currently five lifecycle decorators:
583
584- `@postinit` fires at the end of `Ravel.init()`
585- `@prelisten` fires at the beginning of `Ravel.listen()`
586- `@postlisten` fires at the end of `Ravel.listen()`
587- `@preclose` fires at the beginning of `Ravel.close()`
588- `@koaconfig` fires during `Ravel.init()`, after Ravel is finished configuring the underlying `koa` app object with global middleware. Methods decorated with `@koaconfig` receive a reference to the underlying `koa` app object for customization. This decorator is meant for exceptional circumstances, since (unnecessarily) global middleware constitutes a hot path and can lead to inefficiency.
589
590### Ravel.Routes
591> [<small>View API docs &#128366;</small>](http://raveljs.github.io/docs/latest/core/routes.js.html)
592
593`Routes` are Ravel's abstraction of `koa`. They provide Ravel with a simple mechanism for registering `koa` routes, which should (generally) only be used for serving templated pages or static content (not for building RESTful APIs, for which `Ravel.Resource` is more applicable). Extend this abstract superclass to create a `Routes` module.
594
595Like `Module`s, `Routes` classes support dependency injection, allowing easy connection of application logic and web layers.
596
597Endpoints are created within a `Routes` class by creating an `async` method and then decorating it with [`@mapping`](http://raveljs.github.io/docs/latest/core/decorators/mapping.js.html). The `@mapping` decorator indicates the path for the route (concatenated with the base path passed to `super()` in the `constructor`), as well as the HTTP verb. The method handler accepts a single argument `ctx` which is a [koa context](http://koajs.com/#context). Savvy readers with `koa` experience will note that, within the handler, `this` refers to the instance of the Routes class (to make it easy to access injected `Module`s), and the passed `ctx` argument is a reference to the `koa` context.
598
599*routes/my-routes.js*
600```js
601const inject = require('ravel').inject;
602const Routes = require('ravel').Routes;
603const mapping = Routes.mapping; // Ravel decorator for mapping a method to an endpoint
604const before = Routes.before; // Ravel decorator for conneting middleware to an endpoint
605
606// you can inject your own Modules and npm dependencies into Routes
607@inject('koa-bodyparser', 'fs', 'custom-module')
608class MyRoutes extends Routes {
609 // The constructor for a `Routes` class must call `super()` with the base
610 // path for all routes within that class. Koa path parameters such as
611 // :something are supported.
612 constructor (bodyParser, fs, custom) {
613 super('/'); // base path for all routes in this class
614 this.bodyParser = bodyParser(); // make bodyParser middleware available
615 this.fs = fs;
616 this.custom = custom;
617 }
618
619 // will map to GET /app
620 @mapping(Routes.GET, 'app'); // Koa path parameters such as :something are supported
621 @before('bodyParser') // use bodyParser middleware before handler. Matches this.bodyParser created in the constructor.
622 async appHandler (ctx) {
623 ctx.status = 200;
624 ctx.body = '<!doctype html><html></html>';
625 // ctx is a koa context object.
626 // await on Promises and use ctx to create a body/status code for response
627 // throw a Ravel.Error to automatically set an error status code
628 }
629}
630
631module.exports = MyRoutes;
632```
633
634#### Registering Routes
635
636Much like `Module`s, `Routes` can be added to your Ravel application via `app.routes('path/to/routes')`:
637
638*app.js*
639```js
640// ...
641const app = new Ravel();
642// you must add routes one at a time. Directory scanning is not supported.
643app.routes('./routes/my-routes');
644```
645
646### Ravel.Resource
647> [<small>View API docs &#128366;</small>](http://raveljs.github.io/docs/latest/core/resource.js.html)
648
649What might be referred to as a *controller* in other frameworks, a `Resource` module defines HTTP methods on an endpoint. `Resource`s also support dependency injection, allowing for the easy creation of RESTful interfaces to your `Module`-based application logic. Resources are really just a thin wrapper around `Routes`, using specially-named handler methods (`get`, `getAll`, `post`, `put`, `putAll`, `delete`, `deleteAll`) instead of `@mapping`. This convention-over-configuration approach makes it easier to write proper REST APIs with less code, and is recommended over ~~carefully chosen~~ `@mapping`s in a `Routes` class. Omitting any or all of the specially-named handler functions is fine, and will result in a `501 NOT IMPLEMENTED` status when that particular method/endpoint is requested. `Resource`s inherit all the properties, methods and decorators of `Routes`. See [core/routes](routes.js.html) for more information. Note that `@mapping` does not apply to `Resources`.
650
651As with `Routes` classes, `Resource` handler methods are `async` functions which receive a [koa context](http://koajs.com/#context) as their only argument.
652
653*resources/person-resource.js*
654```js
655const inject = require('ravel').inject;
656const Resource = require('ravel').Resource;
657const before = Routes.before;
658
659// you can inject your own Modules and npm dependencies into Resources
660@inject('koa-bodyparser', 'fs', 'custom-module')
661class PersonResource extends Resource {
662 constructor(convert, bodyParser, fs, custom) {
663 super('/person'); // base path for all routes in this class
664 this.bodyParser = bodyParser(); // make bodyParser middleware available
665 this.fs = fs;
666 this.custom = custom;
667 }
668
669 // will map to GET /person
670 @before('bodyParser') // use bodyParser middleware before handler
671 async getAll (ctx) {
672 // ctx is a koa context object.
673 // await on Promises, and set ctx.body to create a body for response
674 // "OK" status code will be chosen automatically unless configured via ctx.status
675 // Extend and throw a Ravel.Error to send an error status code
676 }
677
678 // will map to GET /person/:id
679 async get (ctx) {
680 // can use ctx.params.id in here automatically
681 }
682
683 // will map to POST /person
684 async post (ctx) {}
685
686 // will map to PUT /person
687 async putAll (ctx) {}
688
689 // will map to PUT /person/:id
690 async put (ctx) {}
691
692 // will map to DELETE /person
693 async deleteAll (ctx) {}
694
695 // will map to DELETE /person/:id
696 async delete (ctx) {}
697}
698
699module.exports = PersonResource;
700```
701
702#### Registering Resources
703> [<small>View API docs &#128366;</small>](http://raveljs.github.io/docs/latest/core/resources.js.html)
704
705Much like `Module`s, `Resource`s can be added to your Ravel application via `app.resources('path/to/resources/directory')`:
706
707*app.js*
708```js
709// ...
710const app = new Ravel();
711// directory scanning!
712app.resources('./resources');
713```
714
715### Response Caching
716
717Ravel supports transparent response caching via the `@cache` decorator, which can be applied at both the class and method-level of `Resource`s and `Routes`. Method-level applications of `@cache` override class-level ones.
718
719*Method-level example*
720```js
721const Routes = require('ravel').Routes;
722const mapping = Routes.mapping;
723const cache = Routes.cache;
724
725class MyRoutes extends Routes {
726 constructor () {
727 super('/');
728 }
729
730 @cache // method-level version only applies to this route
731 @mapping(Routes.GET, '/projects/:id')
732 async handler (ctx) {
733 // The response will automatically be cached when this handler is run
734 // for the first time, and then will be served instead of running the
735 // handler for as long as the cached response is available.
736 }
737}
738```
739
740*Class-level example, with options*
741```js
742const Resource = require('ravel').Resource;
743const cache = Resource.cache;
744
745// class-level version applies to all routes in class, overriding any
746// method-level instances of the decorator.
747@cache({expire:60, maxLength: 100}) // expire is measured in seconds. maxLength in bytes.
748class MyResource extends Resource {
749 constructor (bodyParser) {
750 super('/');
751 this.bodyParser = bodyParser();
752 }
753
754 async get(ctx) {
755 // The response will automatically be cached when this handler is run
756 // for the first time, and then will be served instead of running the
757 // handler for as long as the cached response is available (60 seconds).
758 }
759}
760```
761
762### Database Providers
763> [<small>View API docs &#128366;</small>](http://raveljs.github.io/docs/latest/db/database_provider.js.html)
764
765A `DatabaseProvider` is a lightweight wrapper for a `node` database library (such as [node-mysql](https://github.com/felixge/node-mysql)) which performs all the complex set-up and configuration of the library automatically, and registers simple parameters which you must `app.set` (such as the database host ip). The true purpose of `DatabaseProvider`s is to reduce boilerplate code between applications, as well as facilitate Ravel's transaction-per-request system (coming up [next](#transaction-per-request)). You may use as many different `DatbaseProvider`s as you wish in your application. Here's an example pulled from [`ravel-mysql-provider`](https://github.com/raveljs/ravel-mysql-provider):
766
767#### Example Setup
768
769*app.js*
770```javascript
771const app = new require('ravel')();
772const MySQLProvider = require('ravel-mysql-provider');
773new MySQLProvider(app, 'mysql');
774// ... other providers and parameters
775app.init();
776// ... the rest of your Ravel app
777```
778
779#### Example Configuration
780
781*.ravelrc.json*
782```json
783{
784 "mysql options": {
785 "host": "localhost",
786 "port": 3306,
787 "user": "root",
788 "password": "a password",
789 "database": "mydatabase",
790 "idleTimeoutMillis": 5000,
791 "connectionLimit": 10
792 }
793}
794```
795
796#### List of Ravel `DatabaseProvider`s
797
798Ravel currently supports several `DatabaseProvider`s via external libraries.
799
800 - [`ravel-mysql-provider`](https://github.com/raveljs/ravel-mysql-provider)
801 - [`ravel-rethinkdb-provider`](https://github.com/raveljs/ravel-rethinkdb-provider)
802 - [`ravel-neo4j-provider`](https://github.com/raveljs/ravel-neo4j-provider)
803
804> If you've written a `DatabaseProvider` and would like to see it on this list, contact us or open an issue/PR against this README!
805
806### Transaction-per-request
807> [<small>View API docs &#128366;</small>](http://raveljs.github.io/docs/latest/db/decorators/transaction.js.html)
808
809The `@transaction` decorator is Ravel's way of automatically opening (and managing) database connections for a `Routes` or `Resource` handler method. It is available for import as `Routes.transaction` or `Resource.transaction`.
810
811When used at the method-level, `@transaction` opens connections for that specific handler method. When used at the class-level, it open connections for all handler methods in that `Route` or `Resource` class.
812
813Connections are available within the handler method as an object `ctx.transaction`, which contains connections as values and `DatabaseProvider` names as keys. Connections will be closed automatically when the endpoint responds (**do not close them yourself**), and will automatically roll-back changes if a `DatabaseProvider` supports it (generally a SQL-only feature).
814
815*resources/person-resource.js*
816```js
817const Resource = require('ravel').Resource;
818const transaction = Resource.transaction;
819
820class PersonResource extends Resource {
821 constructor (bodyParser, fs, custom) {
822 super('/person');
823 }
824
825 // maps to GET /person/:id
826 @transaction('mysql') // this is the name exposed by ravel-mysql-provider
827 async get (ctx) {
828 // TIP: Don't write complex logic here. Pass ctx.transaction into
829 // a Module function which returns a Promise! This example is
830 // just for demonstration purposes.
831 ctx.body = await new Promise((resolve, reject) => {
832 // ctx.transaction.mysql is a https://github.com/felixge/node-mysql connection
833 ctx.transaction.mysql.query('SELECT 1', (err, rows) => {
834 if (err) return reject(err);
835 resolve(rows);
836 });
837 });
838 }
839}
840module.exports = PersonResource;
841```
842
843### Scoped Transactions
844> [<small>View API docs &#128366;</small>](http://raveljs.github.io/docs/latest/core/module.js.html)
845
846Sometimes, you may need to open a transaction outside of a code path triggered by an HTTP request. Good examples of this might include database initialization at application start-time, or logic triggered by a websocket connection. In these cases, a `Module` class can open a `scoped` transaction using the names of the DatabaseProviders you are interested in, and an `async` function (scope) in which to use the connections. Scoped transactions only exist for the scope of the `async` function and are automatically cleaned up at the end of the function. It is best to view `Module.db.scoped()` as an identical mechanism to `@transaction`, behaving in exactly the same way, with a slightly different API:
847
848*modules/database-initializer.js*
849```js
850const Module = require('ravel').Module;
851const prelisten = Module.prelisten;
852
853class DatabaseInitializer extends Module {
854
855 @prelisten // trigger db init on application startup
856 doDbInit (ctx) {
857 const self = this;
858 // specify one or more providers to open connections to, or none
859 // to open connections to all known DatabaseProviders.
860 this.db.scoped('mysql', async function (ctx) {
861 // this async function behaves like koa middleware,
862 // so feel free to await on promises!
863 await self.createTables(ctx.transaction.mysql);
864 await self.insertRows(ctx.transaction.mysql);
865 // notice that this.transaction is identical to ctx.transaction
866 // from @transaction! It's just a hash of open, named connections
867 // to the DatabaseProviders specified.
868 }).catch((err) => {
869 self.log.error(err.stack);
870 process.exit(1); // in this case, we might want to kill our app if db init fails!
871 });
872 }
873
874 /**
875 * @returns {Promise}
876 */
877 createTables (mysqlConnection) { /* ... */ }
878
879 /**
880 * @returns {Promise}
881 */
882 insertRows (mysqlConnection) { /* ... */ }
883}
884
885module.exports = DatabaseInitializer;
886```
887
888### Authentication Providers
889> [<small>View API docs &#128366;</small>](http://raveljs.github.io/docs/latest/auth/authentication_provider.js.html)
890
891An `AuthenticationProvider` is a lightweight wrapper for a [Passport](https://github.com/jaredhanson/passport) provider library (such as [passport-github](https://github.com/jaredhanson/passport-github)) which performs all the complex set-up and configuration of the library automatically, and registers simple parameters which you must `app.set` (such as OAuth client ids and secrets). The purpose of `AuthenticationProvider`s is to reduce boilerplate code between applications, and simplify often complex `Passport` configuration code. You may use as many different `AuthenticationProvider`s as you wish in your application. Here's an example pulled from [`ravel-github-oauth2-provider`](https://github.com/raveljs/ravel-github-oauth2-provider):
892
893#### Example Setup
894
895*app.js*
896```javascript
897const app = new require('ravel')();
898const GitHubProvider = require('ravel-github-oauth2-provider');
899new GitHubProvider(app);
900// ... other providers and parameters
901app.init();
902// ... the rest of your Ravel app
903```
904
905#### Example Configuration
906
907*.ravelrc.json*
908```json
909{
910 "github auth callback url" : "http://localhost:8080",
911 "github auth path": "/auth/github",
912 "github auth callback path": "/auth/github/callback",
913 "github client id": "YOUR_CLIENT_ID",
914 "github client secret" : "YOUR_CLIENT_SECRET"
915}
916```
917
918You'll also need to implement an `@authconfig` module like this:
919
920*modules/authconfig.js*
921```js
922'use strict';
923
924const Ravel = require('ravel');
925const inject = Ravel.inject;
926const Module = Ravel.Module;
927const authconfig = Module.authconfig;
928
929@authconfig
930@inject('user-profiles')
931class AuthConfig extends Module {
932 constructor (userProfiles) {
933 this.userProfiles = userProfiles;
934 }
935 serializeUser (profile) {
936 // serialize profile to session using the id field
937 return Promise.resolve(profile.id);
938 }
939 deserializeUser (id) {
940 // retrieve profile from database using id from session
941 return this.userProfiles.getProfile(id); // a Promise
942 }
943 verify (providerName, ...args) {
944 // this method is roughly equivalent to the Passport verify callback, but
945 // supports multiple simultaneous AuthenticationProviders.
946 // providerName is the name of the provider which needs credentials verified
947 // args is an array containing credentials, such as username/password for
948 // verification against your database, or a profile and OAuth tokens. See
949 // specific AuthenticationProvider library READMEs for more information about
950 // how to implement this method.
951 }
952}
953
954module.exports = AuthConfig;
955```
956
957#### List of Ravel `AuthenticationProvider`s
958
959Ravel currently supports several `AuthenticationProvider`s via external libraries.
960
961 - [`ravel-github-oauth2-provider`](https://github.com/raveljs/ravel-github-oauth2-provider)
962 - [`ravel-google-oauth2-provider`](https://github.com/raveljs/ravel-google-oauth2-provider)
963
964> If you've written an `AuthenticationProvider` and would like to see it on this list, contact us or open an issue/PR against this README!
965
966### Authentication
967> [<small>View API docs &#128366;</small>](http://raveljs.github.io/docs/latest/auth/decorators/authenticated.js.html)
968
969Once you've registered an `AuthenticationProvider`, requiring users to have an authenticated session to access a `Routes` or `Resource` endpoint is accomplished via the `@authenticated` decorator, which can be used at the class or method level:
970
971*Note: the @authenticated decorator works the same way on `Routes` and `Resource` classes/methods*
972```js
973const Routes = require('ravel').Routes;
974const mapping = Routes.mapping;
975const authenticated = Routes.authenticated;
976
977@authenticated // protect all endpoints in this Routes class
978class MyRoutes extends Routes {
979 constructor () {
980 super('/');
981 }
982
983 @authenticated({redirect: true}) // protect one endpoint specifically
984 @mapping(Routes.GET, 'app')
985 async handler (ctx) {
986 // will redirect to app.get('login route') if not signed in
987 }
988}
989```
990
991## Deployment and Scaling
992
993Ravel is designed for horizontal scaling, and helps you avoid common pitfalls when designing your node.js backend application. In particular:
994
995 - Session storage in [Redis](https://github.com/antirez/redis) is currently mandatory, ensuring that you can safely replicate your Ravel app safely
996 - The internal [koa](http://koajs.com/) application's `app.proxy` flag is set to `true`.
997 - All Ravel dependencies are strictly locked (i.e. no use of `~` or `^` in `package.json`). This helps foster repeatability between members of your team, as well as between development/testing/production environments. Adherence to semver in the node ecosystem is unfortunately varied at best, so it is recommended that you follow the same practice in your app as well.
998 - While it is possible to color outside the lines, Ravel provides a framework for developing **stateless** backend applications, where all stateful data is stored in external caches or databases.
999
1000It is strongly encouraged that you containerize your Ravel app using an [Alpine-based docker container](https://hub.docker.com/r/mhart/alpine-node/), and then explore technologies such as [docker-compose](https://www.docker.com/products/docker-compose) or [kubernetes](http://kubernetes.io/) to appropriately scale out and link to (at least) the [official redis container](https://hub.docker.com/_/redis/). An example project with a reference `docker-compose` environment for Ravel can be found in the [starter project](https://github.com/raveljs/ravel-github-mariadb-starter).
1001
1002Ravel does not explicitly require [hiredis](https://github.com/redis/hiredis-node), but is is highly recommended that you install it alongside Ravel for improved redis performance.
1003
1004If you are looking for a good way to share `.ravelrc.json` configuration between multiple replicas of the same Ravel app, have a look at [ravel-etcd-config](https://github.com/raveljs/ravel-etcd-config) for easy distributed configuration.