UNPKG

43.7 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 explore 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
72## Architecture
73
74Ravel applications consist of a few basic parts:
75
76- **Modules:** plain old classes which offer a great place to write modular application logic, middleware, authentication logic, etc.
77- **Routes:** a low-level place for general routing logic
78- **Resources:** built on top of `Routes`, `Resource`s are REST-focused
79- **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
80
81If you're doing it right, your applications will consist largely of `Module`s, with a thin layer of `Routes` and `Resource`s on top.
82
83### Modules (and Errors)
84
85`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.
86
87For more information about `Module`s, look at [Ravel.Module](#ravelmodule) below.
88
89*modules/cities.js*
90```javascript
91const Ravel = require('ravel');
92const Error = Ravel.Error;
93const Module = Ravel.Module;
94const inject = Ravel.inject;
95
96/**
97 * First, we'll define an Error we will throw when a requested
98 * city is not found. This Error will be associated with the
99 * HTTP error code 404.
100 */
101class MissingCityError extends Error {
102 constructor (name) {
103 super(`City ${name} does not exist.`, Ravel.httpCodes.NOT_FOUND);
104 }
105}
106
107/**
108 * Our main Module, defining logic for working with Cities
109 */
110@inject('moment')
111class Cities extends Module {
112 constructor (moment) {
113 super();
114 this.moment = moment;
115 this.cities = ['Toronto', 'New York', 'Chicago']; // our fake 'database'
116 }
117
118 getAllCities () {
119 return Promise.resolve(this.cities);
120 }
121
122 getCity (name) {
123 return new Promise((resolve, reject) => {
124 const index = this.cities.indexOf(name);
125 if (index !== -1) {
126 resolve(this.cities[index]);
127 } else {
128 // Ravel will automatically respond with the appropriate HTTP status code!
129 this.log.warn(`User requested unknown city ${name}`);
130 reject(new MissingCityError(name));
131 }
132 });
133 }
134}
135
136// Export Module class
137module.exports = Cities;
138```
139
140### Routes
141
142`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!).
143
144For more information about `Routes`, look at [Ravel.Routes](#ravelroutes) below.
145
146*routes/index.js*
147```javascript
148const Ravel = require('ravel');
149const Routes = Ravel.Routes;
150const inject = Ravel.inject;
151const before = Routes.before; // decorator to add middleware to an endpoint within the Routes
152const mapping = Routes.mapping; // decorator to associate a handler method with an endpoint
153
154@inject('middleware1') // middleware from NPM, or your own modules, etc.
155class ExampleRoutes extends Routes {
156 constructor (middleware1) {
157 super('/'); // base path for all routes in this class. Will be prepended to the @mapping.
158 this.middleware1 = middleware1;
159 // you can also build middleware right here!
160 this.middleware2 = async function (next) {
161 await next;
162 };
163 }
164
165 // bind this method to an endpoint and verb with @mapping. This one will become GET /app
166 @mapping(Routes.GET, 'app')
167 @before('middleware1','middleware2') // use @before to place middleware before appHandler
168 async appHandler (ctx) {
169 // ctx is just a koa context! Have a look at the koa docs to see what methods and properties are available.
170 ctx.body = '<!DOCTYPE html><html><body>Hello World!</body></html>';
171 ctx.status = 200;
172 }
173}
174
175// Export Routes class
176module.exports = ExampleRoutes;
177```
178
179### Resources
180
181What 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.
182
183For more information about `Resource`s, look at [Ravel.Resource](#ravelresouce) below.
184
185*resources/city.js*
186```javascript
187// Resources support dependency injection too!
188// Notice that we have injected our cities Module by name.
189const Ravel = require('ravel');
190const Resource = Ravel.Resource;
191const inject = Ravel.inject;
192const before = Resource.before; // decorator to add middleware to an endpoint within the Resource
193
194// using @before at the class level decorates all endpoint methods with middleware
195@inject('cities')
196class CitiesResource extends Resource {
197 constructor (cities) {
198 super('/cities'); //base path
199 this.cities = cities;
200
201 // some other middleware, which you might have injected from a Module or created here
202 this.anotherMiddleware = async function (next) {
203 await next;
204 };
205 }
206
207 // no need to use @mapping here. Routes methods are automatically mapped using their names.
208 async getAll (ctx) { // just like in Routes, ctx is a koa context.
209 ctx.body = await this.cities.getAllCities();
210 }
211
212 @before('anotherMiddleware') // using @before at the method level decorates this method with middleware
213 async get (ctx) { // get routes automatically receive an endpoint of /cities/:id (in this case).
214 ctx.body = await this.cities.getCity(ctx.params.id);
215 }
216
217 // post, put, putAll, delete and deleteAll are
218 // also supported. Not specifying them for
219 // this resource will result in calls using
220 // those verbs returning HTTP 501 NOT IMPLEMENTED
221
222 // postAll is not supported, because it makes no sense
223}
224
225// Export Resource class
226module.exports = CitiesResource;
227```
228
229### Bringing it all together
230
231*app.js*
232```javascript
233const app = new require('ravel')();
234
235// parameters like this can be supplied via a .ravelrc.json file
236app.set('keygrip keys', ['mysecret']);
237
238app.modules('./modules'); //import all Modules from a directory
239app.resources('./resources'); //import all Resources from a directory
240app.routes('./routes/index.js'); //import all Routes from a file
241
242// start it up!
243app.start();
244```
245
246### Decorator Transpilation
247
248Since 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.
249
250```bash
251$ 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
252# Note, please add babel-plugin-transform-async-to-generator@6.16.0 if you are using Node v6 instead of v7.
253```
254
255*gulpfile.js*
256```js
257const babelConfig = {
258 'retainLines': true,
259 'plugins': ['transform-decorators-legacy'] // add 'transform-async-to-generator' if you are using Node v6 instead of v7
260};
261gulp.task('transpile', function () {
262 return gulp.src('src/**/*.js') // point it at your source directory, containing Modules, Resources and Routes
263 .pipe(plugins.sourcemaps.init())
264 .pipe(plugins.babel(babelConfig))
265 .pipe(plugins.sourcemaps.write('.'))
266 .pipe(gulp.dest('dist')); // your transpiled Ravel app will appear here!
267});
268```
269
270Check out the [starter project](https://github.com/raveljs/ravel-github-mariadb-starter) to see a working example of this build process.
271
272### Running the Application
273
274```bash
275$ node dist/app.js
276```
277
278## API Documentation
279> [<small>View API docs &#128366;</small>](http://raveljs.github.io/docs/latest/)
280
281### Ravel App
282> [<small>View API docs &#128366;</small>](http://raveljs.github.io/docs/latest/index.html#ravel)
283
284A 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`:
285
286*app.js*
287```js
288const Ravel = require('ravel');
289const app = new Ravel();
290
291(async () => {
292 // you'll register managed parameters, and connect Modules, Resources and Routes here
293 await app.init();
294 // you'll set managed parameters here
295 await app.listen();
296})();
297```
298
299### Managed Configuration System
300
301Traditional `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:
302
303#### app.registerParameter
304> [<small>View API docs &#128366;</small>](http://raveljs.github.io/docs/latest/index.html#Ravel#registerParameter)
305
306Create managed parameters with `app.registerParameter()`:
307
308*app.js*
309```js
310const Ravel = require('ravel');
311const app = new Ravel();
312
313// register a new optional parameter
314app.registerParameter('my optional parameter');
315// register a new required parameter
316app.registerParameter('my required parameter', true);
317// register a required parameter with a default value
318app.registerParameter('my third parameter', true, 'some value');
319
320(async () => {
321 await app.init();
322 await app.listen();
323})();
324```
325
326Many Ravel plugin libraries will automatically create parameters which you will have to supply values for. These parameters will be documented in their `README.md`.
327
328#### app.set
329> [<small>View API docs &#128366;</small>](http://raveljs.github.io/docs/latest/index.html#Ravel#set)
330
331Provide values via `app.set()`. Setting an unknown parameter will result in an `Error`.
332
333*app.js*
334```js
335const Ravel = require('ravel');
336const app = new Ravel();
337
338// register a new optional parameter
339app.registerParameter('my optional parameter');
340
341(async () => {
342 await app.init();
343
344 // set a value
345 app.set('my optional parameter', 'some value');
346 // this won't work:
347 app.set('an unknown parameter', 'some value');
348
349 await app.listen();
350})();
351```
352
353#### app.get
354> [<small>View API docs &#128366;</small>](http://raveljs.github.io/docs/latest/index.html#Ravel#get)
355
356Retrieve values via `app.get()`. Retrieving an unknown parameter will result in an `Error`.
357
358*app.js*
359```js
360const Ravel = require('ravel');
361const app = new Ravel();
362
363// register a new parameter
364app.registerParameter('my required parameter', true, 'default value');
365
366(async () => {
367 await app.init();
368
369 // set a value
370 app.set('my required parameter', 'some value');
371 // get a value
372 app.get('my required parameter') === 'some value';
373 // this won't work:
374 // app.get('an unknown parameter');
375
376 await app.listen();
377})();
378```
379
380#### Core parameters
381
382Ravel has several core parameters:
383
384```js
385// you have to set these:
386app.set('keygrip keys', ['my super secret key']);
387
388// these are optional (default values are shown):
389app.set('redis host', undefined); // set to point to an external redis server (required for horizontal scaling).
390app.set('redis port', 6379);
391app.set('redis password', undefined);
392app.set('redis max retries', 10); // connection retries
393app.set('port', 8080); // port the app will run on
394app.set('session key', 'koa.sid'); // the cookie name to use for sessions
395app.set('session max age', null); // session maxAge (default never expires)
396app.set('app route', '/'); // if you have a UI, this is the path users will be sent to when they are logged in
397app.set('login route', '/login'); // if users aren't logged in and you redirect them, this is where they'll be sent
398app.set('koa public directory', undefined); // if you want to statically serve a directory
399app.set('koa view directory', undefined); // for templated views (EJS, Pug, etc.)
400app.set('koa view engine', undefined); // for templated views (EJS, Pug, etc.)
401app.set('koa favicon path', undefined); // favicon middleware configuration
402```
403
404#### .ravelrc.json
405
406To 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).
407
408*.ravelrc.json*
409```
410{
411 "keygrip keys": ["my super secret key"]
412}
413```
414
415### Ravel.Error
416> [<small>View API docs &#128366;</small>](http://raveljs.github.io/docs/latest/index.html#Ravel.Error)
417
418This 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.
419
420*at the top of some `Module`, `Resource` or `Routes` file (we'll get to this next)*
421```js
422const Ravel = require('ravel');
423/**
424 * Thrown when a user tries to POST something unexpected to /upload
425 */
426class UploadError extends Ravel.Error {
427 constructor (msg) {
428 super(msg, Ravel.httpCodes.BAD_REQUEST);
429 }
430}
431```
432
433### Ravel.Module
434> [<small>View API docs &#128366;</small>](http://raveljs.github.io/docs/latest/index.html#module)
435
436`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).
437
438Here's a simple module:
439
440*modules/my-module.js*
441```js
442const Ravel = require('ravel');
443const inject = Ravel.inject; // Ravel's dependency injection decorator
444const Module = Ravel.Module; // base class for Ravel Modules
445
446// inject a custom ravel Module (or your plain classes) beside npm dependencies!
447@inject('path', 'fs', 'custom-module', 'plain-class')
448class MyModule extends Module {
449 constructor (path, fs, custom, plain) { // @inject'd modules are available here as parameters
450 super();
451 this.path = path;
452 this.fs = fs;
453 this.custom = custom;
454 this.plain = plain;
455 }
456
457 // implement any methods you like :)
458 aMethod () {
459 // ...
460 }
461
462 async anAsyncMethod () {
463 // ...
464 }
465}
466
467module.exports = MyModule; // you must export your Module so that Ravel can require() it.
468```
469
470#### Dependency Injection and Module Registration
471> [<small>View API docs &#128366;</small>](http://raveljs.github.io/docs/latest/index.html#inject)
472
473Ravel's *dependency injection* system is meant to address several issues with traditional `require()`s:
474
475- 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.
476- Cyclical dependencies between modules are not always obvious in a large codebase, and can result in unexpected behaviour.
477
478Ravel addresses this with the the [`@inject`](http://raveljs.github.io/docs/latest/index.html#inject) decorator:
479
480*modules/my-module.js*
481```js
482const Ravel = require('ravel');
483const inject = Ravel.inject;
484const Module = Ravel.Module;
485
486@inject('another-module') // inject another Module from your project without require()!
487class MyModule extends Module {
488 constructor (another) { // @inject'd modules are available here as parameters
489 super();
490 this.another = another;
491 }
492}
493module.exports = MyModule;
494```
495
496The injection name of `another-module` comes from its filename, and can be overriden in `app.js`:
497
498*app.js*
499```js
500// ...
501const app = new Ravel();
502// the first argument is the path to the module file.
503// the second is the name you assign for dependency injection.
504app.module('./modules/my-module', 'my-module');
505app.module('./modules/another-module', 'another-module');
506// assigning names manually becomes tedious fast, so Ravel can
507// infer the names from the names of your files when you use
508// app.modules to scan a directory:
509app.modules('./modules'); // this would register modules with the same names as above
510```
511
512`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`.
513
514`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.).
515
516To 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:
517
518```js
519const Ravel = require('ravel');
520const inject = Ravel.inject;
521const Module = Ravel.Module;
522
523@inject('another-module', 'path', 'moment') // anything that can be require()d can be @injected
524class MyModule extends Module {
525 constructor (another, path, moment) {
526 super();
527 // ...
528 }
529}
530module.exports = MyModule;
531```
532
533#### Module Namespacing
534
535In 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:
536
537```
538app.js
539.ravelrc.json
540modules/
541 core/
542 my-module.js
543 util/
544 my-module.js
545```
546
547Then, import the `Module` directory as before, using `app.modules()`:
548
549*app.js*
550```js
551// ...
552const app = new Ravel();
553app.modules('./modules');
554// core/my-module can now be injected using @inject(core.my-module)!
555// util/my-module can now be injected using @inject(util.my-module)!
556```
557
558> Essentially, Ravel ignores the path you pass to `app.modules()` and uses any remaining path components to namespace `Module`s.
559
560#### Lifecycle Decorators
561> [<small>View API docs &#128366;</small>](http://raveljs.github.io/docs/latest/index.html#Module.postinit)
562
563`Module`s are also a great place to define logic which should run at particular points during the Ravel lifecycle. Decorating a `Module` method with a lifecycle decorator appropriately results in that method firing exactly once at the specified time (with the exception of `@interval`, of course):
564
565```js
566const Ravel = require('ravel');
567const Module = Ravel.Module;
568const prelisten = Module.prelisten;
569
570class MyInitModule extends Module {
571 // ...
572 @prelisten
573 initDBTables () {
574 // ...
575 }
576}
577module.exports = MyInitModule;
578```
579
580There are currently six lifecycle decorators:
581
582- `@postinit` fires at the end of `Ravel.init()`
583- `@prelisten` fires at the beginning of `Ravel.listen()`
584- `@postlisten` fires at the end of `Ravel.listen()`
585- `@preclose` fires at the beginning of `Ravel.close()`
586- `@interval(1000)` fires at the end of `Ravel.listen()` and then repeatedly at the specified interval until `Ravel.close()`
587- `@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.
588
589### Ravel.Routes
590> [<small>View API docs &#128366;</small>](http://raveljs.github.io/docs/latest/index.html#routes)
591
592`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.
593
594Like `Module`s, `Routes` classes support dependency injection, allowing easy connection of application logic and web layers.
595
596Endpoints are created within a `Routes` class by creating an `async` method and then decorating it with [`@mapping`](http://raveljs.github.io/docs/latest/index.html#Routes.mapping). 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.
597
598*routes/my-routes.js*
599```js
600const inject = require('ravel').inject;
601const Routes = require('ravel').Routes;
602const mapping = Routes.mapping; // Ravel decorator for mapping a method to an endpoint
603const before = Routes.before; // Ravel decorator for conneting middleware to an endpoint
604
605// you can inject your own Modules and npm dependencies into Routes
606@inject('koa-bodyparser', 'fs', 'custom-module')
607class MyRoutes extends Routes {
608 // The constructor for a `Routes` class must call `super()` with the base
609 // path for all routes within that class. Koa path parameters such as
610 // :something are supported.
611 constructor (bodyParser, fs, custom) {
612 super('/'); // base path for all routes in this class
613 this.bodyParser = bodyParser(); // make bodyParser middleware available
614 this.fs = fs;
615 this.custom = custom;
616 }
617
618 // will map to GET /app
619 @mapping(Routes.GET, 'app'); // Koa path parameters such as :something are supported
620 @before('bodyParser') // use bodyParser middleware before handler. Matches this.bodyParser created in the constructor.
621 async appHandler (ctx) {
622 ctx.status = 200;
623 ctx.body = '<!doctype html><html></html>';
624 // ctx is a koa context object.
625 // await on Promises and use ctx to create a body/status code for response
626 // throw a Ravel.Error to automatically set an error status code
627 }
628}
629
630module.exports = MyRoutes;
631```
632
633#### Registering Routes
634
635Much like `Module`s, `Routes` can be added to your Ravel application via `app.routes('path/to/routes')`:
636
637*app.js*
638```js
639// ...
640const app = new Ravel();
641// you must add routes one at a time. Directory scanning is not supported.
642app.routes('./routes/my-routes');
643```
644
645### Ravel.Resource
646> [<small>View API docs &#128366;</small>](http://raveljs.github.io/docs/latest/index.html#resource)
647
648What 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](http://raveljs.github.io/docs/latest/index.html#routes) for more information. Note that `@mapping` does not apply to `Resources`.
649
650As with `Routes` classes, `Resource` handler methods are `async` functions which receive a [koa context](http://koajs.com/#context) as their only argument.
651
652*resources/person-resource.js*
653```js
654const inject = require('ravel').inject;
655const Resource = require('ravel').Resource;
656const before = Routes.before;
657
658// you can inject your own Modules and npm dependencies into Resources
659@inject('koa-bodyparser', 'fs', 'custom-module')
660class PersonResource extends Resource {
661 constructor(convert, bodyParser, fs, custom) {
662 super('/person'); // base path for all routes in this class
663 this.bodyParser = bodyParser(); // make bodyParser middleware available
664 this.fs = fs;
665 this.custom = custom;
666 }
667
668 // will map to GET /person
669 @before('bodyParser') // use bodyParser middleware before handler
670 async getAll (ctx) {
671 // ctx is a koa context object.
672 // await on Promises, and set ctx.body to create a body for response
673 // "OK" status code will be chosen automatically unless configured via ctx.status
674 // Extend and throw a Ravel.Error to send an error status code
675 }
676
677 // will map to GET /person/:id
678 async get (ctx) {
679 // can use ctx.params.id in here automatically
680 }
681
682 // will map to POST /person
683 async post (ctx) {}
684
685 // will map to PUT /person
686 async putAll (ctx) {}
687
688 // will map to PUT /person/:id
689 async put (ctx) {}
690
691 // will map to DELETE /person
692 async deleteAll (ctx) {}
693
694 // will map to DELETE /person/:id
695 async delete (ctx) {}
696}
697
698module.exports = PersonResource;
699```
700
701#### Registering Resources
702> [<small>View API docs &#128366;</small>](http://raveljs.github.io/docs/latest/index.html#Ravel#resources)
703
704Much like `Module`s, `Resource`s can be added to your Ravel application via `app.resources('path/to/resources/directory')`:
705
706*app.js*
707```js
708// ...
709const app = new Ravel();
710// directory scanning!
711app.resources('./resources');
712```
713
714### Response Caching
715
716Ravel 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.
717
718*Method-level example*
719```js
720const Routes = require('ravel').Routes;
721const mapping = Routes.mapping;
722const cache = Routes.cache;
723
724class MyRoutes extends Routes {
725 constructor () {
726 super('/');
727 }
728
729 @cache // method-level version only applies to this route
730 @mapping(Routes.GET, '/projects/:id')
731 async handler (ctx) {
732 // The response will automatically be cached when this handler is run
733 // for the first time, and then will be served instead of running the
734 // handler for as long as the cached response is available.
735 // If this handler throws an exception, then that response will not be cached.
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/index.html#databaseprovider)
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
775(async () => {
776 await app.init();
777})();
778// ... the rest of your Ravel app
779```
780
781#### Example Configuration
782
783*.ravelrc.json*
784```json
785{
786 "mysql options": {
787 "host": "localhost",
788 "port": 3306,
789 "user": "root",
790 "password": "a password",
791 "database": "mydatabase",
792 "idleTimeoutMillis": 5000,
793 "connectionLimit": 10
794 }
795}
796```
797
798#### List of Ravel `DatabaseProvider`s
799
800Ravel currently supports several `DatabaseProvider`s via external libraries.
801
802 - [`ravel-mysql-provider`](https://github.com/raveljs/ravel-mysql-provider)
803 - [`ravel-rethinkdb-provider`](https://github.com/raveljs/ravel-rethinkdb-provider)
804 - [`ravel-neo4j-provider`](https://github.com/raveljs/ravel-neo4j-provider)
805
806> 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!
807
808### Transaction-per-request
809> [<small>View API docs &#128366;</small>](http://raveljs.github.io/docs/latest/index.html#transaction)
810
811The `@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`.
812
813When 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.
814
815Connections 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).
816
817*resources/person-resource.js*
818```js
819const Resource = require('ravel').Resource;
820const transaction = Resource.transaction;
821
822class PersonResource extends Resource {
823 constructor (bodyParser, fs, custom) {
824 super('/person');
825 }
826
827 // maps to GET /person/:id
828 @transaction('mysql') // this is the name exposed by ravel-mysql-provider
829 async get (ctx) {
830 // TIP: Don't write complex logic here. Pass ctx.transaction into
831 // a Module function which returns a Promise! This example is
832 // just for demonstration purposes.
833 ctx.body = await new Promise((resolve, reject) => {
834 // ctx.transaction.mysql is a https://github.com/felixge/node-mysql connection
835 ctx.transaction.mysql.query('SELECT 1', (err, rows) => {
836 if (err) return reject(err);
837 resolve(rows);
838 });
839 });
840 }
841}
842module.exports = PersonResource;
843```
844
845### Scoped Transactions
846> [<small>View API docs &#128366;</small>](http://raveljs.github.io/docs/latest/index.html#Module#db)
847
848Sometimes, 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:
849
850*modules/database-initializer.js*
851```js
852const Module = require('ravel').Module;
853const prelisten = Module.prelisten;
854
855class DatabaseInitializer extends Module {
856
857 @prelisten // trigger db init on application startup
858 doDbInit (ctx) {
859 const self = this;
860 // specify one or more providers to open connections to, or none
861 // to open connections to all known DatabaseProviders.
862 this.db.scoped('mysql', async function (ctx) {
863 // this async function behaves like koa middleware,
864 // so feel free to await on promises!
865 await self.createTables(ctx.transaction.mysql);
866 await self.insertRows(ctx.transaction.mysql);
867 // notice that this.transaction is identical to ctx.transaction
868 // from @transaction! It's just a hash of open, named connections
869 // to the DatabaseProviders specified.
870 }).catch((err) => {
871 self.log.error(err.stack);
872 process.exit(1); // in this case, we might want to kill our app if db init fails!
873 });
874 }
875
876 /**
877 * @returns {Promise}
878 */
879 createTables (mysqlConnection) { /* ... */ }
880
881 /**
882 * @returns {Promise}
883 */
884 insertRows (mysqlConnection) { /* ... */ }
885}
886
887module.exports = DatabaseInitializer;
888```
889
890### Authentication Providers
891> [<small>View API docs &#128366;</small>](http://raveljs.github.io/docs/latest/index.html#authenticationprovider)
892
893An `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):
894
895#### Example Setup
896
897*app.js*
898```javascript
899const app = new require('ravel')();
900const GitHubProvider = require('ravel-github-oauth2-provider');
901new GitHubProvider(app);
902// ... other providers and parameters
903(async () => {
904 await app.init();
905});
906// ... the rest of your Ravel app
907```
908
909#### Example Configuration
910
911*.ravelrc.json*
912```json
913{
914 "github auth callback url" : "http://localhost:8080",
915 "github auth path": "/auth/github",
916 "github auth callback path": "/auth/github/callback",
917 "github client id": "YOUR_CLIENT_ID",
918 "github client secret" : "YOUR_CLIENT_SECRET"
919}
920```
921
922You'll also need to implement an `@authconfig` module like this:
923
924*modules/authconfig.js*
925```js
926'use strict';
927
928const Ravel = require('ravel');
929const inject = Ravel.inject;
930const Module = Ravel.Module;
931const authconfig = Module.authconfig;
932
933@authconfig
934@inject('user-profiles')
935class AuthConfig extends Module {
936 constructor (userProfiles) {
937 this.userProfiles = userProfiles;
938 }
939 serializeUser (profile) {
940 // serialize profile to session using the id field
941 return Promise.resolve(profile.id);
942 }
943 deserializeUser (id) {
944 // retrieve profile from database using id from session
945 return this.userProfiles.getProfile(id); // a Promise
946 }
947 verify (providerName, ...args) {
948 // this method is roughly equivalent to the Passport verify callback, but
949 // supports multiple simultaneous AuthenticationProviders.
950 // providerName is the name of the provider which needs credentials verified
951 // args is an array containing credentials, such as username/password for
952 // verification against your database, or a profile and OAuth tokens. See
953 // specific AuthenticationProvider library READMEs for more information about
954 // how to implement this method.
955 }
956}
957
958module.exports = AuthConfig;
959```
960
961#### List of Ravel `AuthenticationProvider`s
962
963Ravel currently supports several `AuthenticationProvider`s via external libraries.
964
965 - [`ravel-github-oauth2-provider`](https://github.com/raveljs/ravel-github-oauth2-provider)
966 - [`ravel-google-oauth2-provider`](https://github.com/raveljs/ravel-google-oauth2-provider)
967
968> 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!
969
970### Authentication
971> [<small>View API docs &#128366;</small>](http://raveljs.github.io/docs/latest/index.html#authenticated)
972
973Once 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:
974
975*Note: the @authenticated decorator works the same way on `Routes` and `Resource` classes/methods*
976```js
977const Routes = require('ravel').Routes;
978const mapping = Routes.mapping;
979const authenticated = Routes.authenticated;
980
981@authenticated // protect all endpoints in this Routes class
982class MyRoutes extends Routes {
983 constructor () {
984 super('/');
985 }
986
987 @authenticated({redirect: true}) // protect one endpoint specifically
988 @mapping(Routes.GET, 'app')
989 async handler (ctx) {
990 // will redirect to app.get('login route') if not signed in
991 }
992}
993```
994
995## Deployment and Scaling
996
997Ravel is designed for horizontal scaling, and helps you avoid common pitfalls when designing your node.js backend application. In particular:
998
999 - Session storage in [Redis](https://github.com/antirez/redis) is highly recommended. Without it, you cannot safely replicate your Ravel app. When deploying multiple replicas of your Ravel app, be sure to `app.set('redis host')` to point to an external, shared `redis` server.
1000 - The internal [koa](http://koajs.com/) application's `app.proxy` flag is set to `true`.
1001 - 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.
1002 - 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.
1003
1004It 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).
1005
1006Ravel 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.
1007
1008If 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.