UNPKG

41.8 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 - [Database Providers](#database-providers)
32 - [Transaction-per-request](#transaction-per-request)
33 - [Scoped Transactions](#scoped-transactions)
34 - [Authentication Providers](#authentication-providers)
35 - [Authentication](#authentication)
36- [Deployment and Scaling](#deployment-and-scaling)
37
38<!-- /TOC -->
39
40## Introduction
41
42Ravel 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:
43
44- A standard set of well-defined architectural components so that your code stays **organized**
45- Rapid **REST API** definition
46- Easy **bootstrapping** via an enforced, reference configuration of [koa](http://koajs.com/) with critical middleware
47- Dependency injection (instead of relative `require`s)
48
49And a few other features, plucked from popular back-end frameworks:
50
51- Transaction-per-request
52- Simple authentication and authentication configuration (no complex [passport](https://github.com/jaredhanson/passport) setup)
53- Externalized session storage for horizontal scalability
54
55Ravel is layered on top of awesome technologies, including:
56- [koa](http://koajs.com/)
57- [Passport](https://github.com/jaredhanson/passport)
58- [Intel](https://github.com/seanmonstar/intel)
59- [Redis](https://github.com/antirez/redis)
60- [docker](http://docker.com)
61
62
63## Installation
64
65> As Ravel uses async/await and several other ES2015/2016 features, you will need to use a 7.6.x+ distribution of node
66
67```bash
68$ npm install ravel
69```
70
71Ravel 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:
72
73```bash
74$ docker run -d -p 6379:6379 redis
75```
76
77## Architecture
78
79Ravel applications consist of a few basic parts:
80
81- **Modules:** plain old classes which offer a great place to write modular application logic, middleware, authentication logic, etc.
82- **Routes:** a low-level place for general routing logic
83- **Resources:** built on top of `Routes`, `Resource`s are REST-focused
84- **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
85
86If you're doing it right, your applications will consist largely of `Module`s, with a thin layer of `Routes` and `Resource`s on top.
87
88### Modules (and Errors)
89
90`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.
91
92For more information about `Module`s, look at [Ravel.Module](#ravelmodule) below.
93
94*modules/cities.js*
95```javascript
96const Ravel = require('ravel');
97const Error = Ravel.Error;
98const Module = Ravel.Module;
99const inject = Ravel.inject;
100
101/**
102 * First, we'll define an Error we will throw when a requested
103 * city is not found. This Error will be associated with the
104 * HTTP error code 404.
105 */
106class MissingCityError extends Error {
107 constructor (name) {
108 super(`City ${name} does not exist.`, Ravel.httpCodes.NOT_FOUND);
109 }
110}
111
112/**
113 * Our main Module, defining logic for working with Cities
114 */
115@inject('moment')
116class Cities extends Module {
117 constructor (moment) {
118 super();
119 this.moment = moment;
120 this.db = ['Toronto', 'New York', 'Chicago']; // our fake 'database'
121 }
122
123 getAllCities () {
124 return Promise.resolve(c);
125 }
126
127 getCity (name) {
128 return new Promise((resolve, reject) => {
129 const index = this.db.indexOf(name);
130 if (index) {
131 resolve(this.db[index]);
132 } else {
133 this.log.warn(`User requested unknown city ${name}`);
134 // Ravel will automatically respond with the appropriate HTTP status code!
135 reject(new MissingCityError(name));
136 }
137 });
138 }
139}
140
141// Export Module class
142module.exports = Cities;
143```
144
145### Routes
146
147`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!).
148
149For more information about `Routes`, look at [Ravel.Routes](#ravelroutes) below.
150
151*routes/index.js*
152```javascript
153const Ravel = require('ravel');
154const Routes = Ravel.Routes;
155const inject = Ravel.inject;
156const before = Routes.before; // decorator to add middleware to an endpoint within the Routes
157const mapping = Routes.mapping; // decorator to associate a handler method with an endpoint
158
159@inject('middleware1') // middleware from NPM, or your own modules, etc.
160class ExampleRoutes extends Routes {
161 constructor (middleware1) {
162 super('/'); // base path for all routes in this class. Will be prepended to the @mapping.
163 this.middleware1 = middleware1;
164 // you can also build middleware right here!
165 this.middleware2 = async function (next) {
166 await next;
167 };
168 }
169
170 // bind this method to an endpoint and verb with @mapping. This one will become GET /app
171 @mapping(Routes.GET, 'app')
172 @before('middleware1','middleware2') // use @before to place middleware before appHandler
173 async appHandler (ctx) {
174 // ctx is just a koa context! Have a look at the koa docs to see what methods and properties are available.
175 ctx.body = '<!DOCTYPE html><html><body>Hello World!</body></html>';
176 ctx.status = 200;
177 }
178}
179
180// Export Routes class
181module.exports = ExampleRoutes;
182```
183
184### Resources
185
186What 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.
187
188For more information about `Resource`s, look at [Ravel.Resource](#ravelresouce) below.
189
190*resources/city.js*
191```javascript
192// Resources support dependency injection too!
193// Notice that we have injected our cities Module by name.
194const Ravel = require('ravel');
195const Resource = Ravel.Resource;
196const inject = Ravel.inject;
197const before = Resource.before; // decorator to add middleware to an endpoint within the Resource
198
199// using @before at the class level decorates all endpoint methods with middleware
200@inject('cities')
201class CitiesResource extends Resource {
202 constructor (cities) {
203 super('/cities'); //base path
204 this.cities = cities;
205
206 // some other middleware, which you might have injected from a Module or created here
207 this.anotherMiddleware = async function (next) {
208 await next;
209 };
210 }
211
212 // no need to use @mapping here. Routes methods are automatically mapped using their names.
213 async getAll (ctx) { // just like in Routes, ctx is a koa context.
214 ctx.body = await this.cities.getAllCities();
215 }
216
217 @before('anotherMiddleware') // using @before at the method level decorates this method with middleware
218 async get (ctx) { // get routes automatically receive an endpoint of /cities/:id (in this case).
219 ctx.body = await this.cities.getCity(ctx.params.id);
220 }
221
222 // post, put, putAll, delete and deleteAll are
223 // also supported. Not specifying them for
224 // this resource will result in calls using
225 // those verbs returning HTTP 501 NOT IMPLEMENTED
226
227 // postAll is not supported, because it makes no sense
228}
229
230// Export Resource class
231module.exports = CitiesResource;
232```
233
234### Bringing it all together
235
236*app.js*
237```javascript
238const app = new require('ravel')();
239
240// parameters like this can be supplied via a .ravelrc.json file
241app.set('keygrip keys', ['mysecret']);
242
243app.modules('./modules'); //import all Modules from a directory
244app.resources('./resources'); //import all Resources from a directory
245app.routes('./routes/index.js'); //import all Routes from a file
246
247// start it up!
248app.start();
249```
250
251### Decorator Transpilation
252
253Since 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.
254
255```bash
256$ 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
257# Note, please add babel-plugin-transform-async-to-generator@6.16.0 if you are using Node v6 instead of v7.
258```
259
260*gulpfile.js*
261```js
262const babelConfig = {
263 'retainLines': true,
264 'plugins': ['transform-decorators-legacy'] // add 'transform-async-to-generator' if you are using Node v6 instead of v7
265};
266gulp.task('transpile', function () {
267 return gulp.src('src/**/*.js') // point it at your source directory, containing Modules, Resources and Routes
268 .pipe(plugins.sourcemaps.init())
269 .pipe(plugins.babel(babelConfig))
270 .pipe(plugins.sourcemaps.write('.'))
271 .pipe(gulp.dest('dist')); // your transpiled Ravel app will appear here!
272});
273```
274
275Check out the [starter project](https://github.com/raveljs/ravel-github-mariadb-starter) to see a working example of this build process.
276
277### Running the Application
278
279```bash
280$ node dist/app.js
281```
282
283## API Documentation
284> [<small>View API docs &#128366;</small>](http://raveljs.github.io/docs/latest/)
285
286### Ravel App
287> [<small>View API docs &#128366;</small>](http://raveljs.github.io/docs/latest/ravel.js.html)
288
289A 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`:
290
291*app.js*
292```js
293const Ravel = require('ravel');
294const app = new Ravel();
295
296// you'll register managed parameters, and connect Modules, Resources and Routes here
297
298app.init();
299
300// you'll set managed parameters here
301
302app.listen();
303```
304
305### Managed Configuration System
306> [<small>View API docs &#128366;</small>](http://raveljs.github.io/docs/latest/core/params.js.html)
307
308Traditional `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:
309
310#### app.registerParameter
311> [<small>View API docs &#128366;</small>](http://raveljs.github.io/docs/latest/core/params.js.html#registerParameter)
312
313Create managed parameters with `app.registerParameter()`:
314
315*app.js*
316```js
317const Ravel = require('ravel');
318const app = new Ravel();
319
320// register a new optional parameter
321app.registerParameter('my optional parameter');
322// register a new required parameter
323app.registerParameter('my required parameter', true);
324// register a required parameter with a default value
325app.registerParameter('my third parameter', true, 'some value');
326
327app.init();
328app.listen();
329```
330
331Many Ravel plugin libraries will automatically create parameters which you will have to supply values for. These parameters will be documented in their `README.md`.
332
333#### app.set
334> [<small>View API docs &#128366;</small>](http://raveljs.github.io/docs/latest/core/params.js.html#set)
335
336Provide values via `app.set()`. Setting an unknown parameter will result in an `Error`.
337
338*app.js*
339```js
340const Ravel = require('ravel');
341const app = new Ravel();
342
343// register a new optional parameter
344app.registerParameter('my optional parameter');
345
346app.init();
347
348// set a value
349app.set('my optional parameter', 'some value');
350// this won't work:
351app.set('an unknown parameter', 'some value');
352
353app.listen();
354```
355
356#### app.get
357> [<small>View API docs &#128366;</small>](http://raveljs.github.io/docs/latest/core/params.js.html#get)
358
359Retrieve values via `app.get()`. Retrieving an unknown parameter will result in an `Error`.
360
361*app.js*
362```js
363const Ravel = require('ravel');
364const app = new Ravel();
365
366// register a new parameter
367app.registerParameter('my required parameter', true, 'default value');
368
369app.init();
370
371// set a value
372app.set('my required parameter', 'some value');
373// get a value
374app.get('my required parameter') === 'some value';
375// this won't work:
376// app.get('an unknown parameter');
377
378app.listen();
379```
380
381#### Core parameters
382
383Ravel has several core parameters:
384
385```js
386// you have to set these:
387app.set('keygrip keys', ['my super secret key']);
388
389// these are optional (default values are shown):
390app.set('redis host', '0.0.0.0');
391app.set('redis port', 6379);
392app.set('redis password', undefined);
393app.set('redis max retries', 10); // connection retries
394app.set('port', 8080); // port the app will run on
395app.set('session key', 'koa.sid'); // the cookie name to use for sessions
396app.set('session max age', null); // session maxAge (default never expires)
397app.set('app route', '/'); // if you have a UI, this is the path users will be sent to when they are logged in
398app.set('login route', '/login'); // if users aren't logged in and you redirect them, this is where they'll be sent
399app.set('koa public directory', undefined); // if you want to statically serve a directory
400app.set('koa view directory', undefined); // for templated views (EJS, Pug, etc.)
401app.set('koa view engine', undefined); // for templated views (EJS, Pug, etc.)
402app.set('koa favicon path', undefined); // favicon middleware configuration
403```
404
405#### .ravelrc.json
406
407To 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).
408
409*.ravelrc.json*
410```
411{
412 "keygrip keys": ["my super secret key"]
413}
414```
415
416### Ravel.Error
417> [<small>View API docs &#128366;</small>](http://raveljs.github.io/docs/latest/util/application_error.js.html)
418
419This 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.
420
421*at the top of some `Module`, `Resource` or `Routes` file (we'll get to this next)*
422```js
423const Ravel = require('ravel');
424/**
425 * Thrown when a user tries to POST something unexpected to /upload
426 */
427class UploadError extends Ravel.Error {
428 constructor (msg) {
429 super(msg, Ravel.httpCodes.BAD_REQUEST);
430 }
431}
432```
433
434### Ravel.Module
435> [<small>View API docs &#128366;</small>](http://raveljs.github.io/docs/latest/core/module.js.html)
436
437`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).
438
439Here's a simple module:
440
441*modules/my-module.js*
442```js
443const Ravel = require('ravel');
444const inject = Ravel.inject; // Ravel's dependency injection decorator
445const Module = Ravel.Module; // base class for Ravel Modules
446
447// inject a custom ravel Module (or your plain classes) beside npm dependencies!
448@inject('path', 'fs', 'custom-module', 'plain-class')
449class MyModule extends Module {
450 constructor (path, fs, custom, plain) { // @inject'd modules are available here as parameters
451 super();
452 this.path = path;
453 this.fs = fs;
454 this.custom = custom;
455 this.plain = plain;
456 }
457
458 // implement any methods you like :)
459 aMethod () {
460 // ...
461 }
462
463 async anAsyncMethod () {
464 // ...
465 }
466}
467
468module.exports = MyModule; // you must export your Module so that Ravel can require() it.
469```
470
471#### Dependency Injection and Module Registration
472> [<small>View API docs &#128366;</small>](http://raveljs.github.io/docs/latest/core/decorators/inject.js.html)
473
474Ravel's *dependency injection* system is meant to address several issues with traditional `require()`s:
475
476- 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.
477- Cyclical dependencies between modules are not always obvious in a large codebase, and can result in unexpected behaviour.
478
479Ravel addresses this with the the [`@inject`](http://raveljs.github.io/docs/latest/core/decorators/inject.js.html) decorator:
480
481*modules/my-module.js*
482```js
483const Ravel = require('ravel');
484const inject = Ravel.inject;
485const Module = Ravel.Module;
486
487@inject('another-module') // inject another Module from your project without require()!
488class MyModule extends Module {
489 constructor (another) { // @inject'd modules are available here as parameters
490 super();
491 this.another = another;
492 }
493}
494module.exports = MyModule;
495```
496
497The injection name of `another-module` comes from its filename, and can be overriden in `app.js`:
498
499*app.js*
500```js
501// ...
502const app = new Ravel();
503// the first argument is the path to the module file.
504// the second is the name you assign for dependency injection.
505app.module('./modules/my-module', 'my-module');
506app.module('./modules/another-module', 'another-module');
507// assigning names manually becomes tedious fast, so Ravel can
508// infer the names from the names of your files when you use
509// app.modules to scan a directory:
510app.modules('./modules'); // this would register modules with the same names as above
511```
512
513`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`.
514
515`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.).
516
517To 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:
518
519```js
520const Ravel = require('ravel');
521const inject = Ravel.inject;
522const Module = Ravel.Module;
523
524@inject('another-module', 'path', 'moment') // anything that can be require()d can be @injected
525class MyModule extends Module {
526 constructor (another, path, moment) {
527 super();
528 // ...
529 }
530}
531module.exports = MyModule;
532```
533
534#### Module Namespacing
535
536In 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:
537
538```
539app.js
540.ravelrc.json
541modules/
542 core/
543 my-module.js
544 util/
545 my-module.js
546```
547
548Then, import the `Module` directory as before, using `app.modules()`:
549
550*app.js*
551```js
552// ...
553const app = new Ravel();
554app.modules('./modules');
555// core/my-module can now be injected using @inject(core.my-module)!
556// util/my-module can now be injected using @inject(util.my-module)!
557```
558
559> Essentially, Ravel ignores the path you pass to `app.modules()` and uses any remaining path components to namespace `Module`s.
560
561#### Lifecycle Decorators
562> [<small>View API docs &#128366;</small>](http://raveljs.github.io/docs/latest/core/decorators/lifecycle.js.html)
563
564`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:
565
566```js
567const Ravel = require('ravel');
568const Module = Ravel.Module;
569const prelisten = Module.prelisten;
570
571class MyInitModule extends Module {
572 // ...
573 @prelisten
574 initDBTables () {
575 // ...
576 }
577}
578module.exports = MyInitModule;
579```
580
581There are currently five lifecycle decorators:
582
583- `@postinit` fires at the end of `Ravel.init()`
584- `@prelisten` fires at the beginning of `Ravel.listen()`
585- `@postlisten` fires at the end of `Ravel.listen()`
586- `@preclose` fires at the beginning of `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/core/routes.js.html)
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/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.
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/core/resource.js.html)
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](routes.js.html) 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/core/resources.js.html)
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### Database Providers
715> [<small>View API docs &#128366;</small>](http://raveljs.github.io/docs/latest/db/database_provider.js.html)
716
717A `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):
718
719#### Example Setup
720
721*app.js*
722```javascript
723const app = new require('ravel')();
724const MySQLProvider = require('ravel-mysql-provider');
725new MySQLProvider(app, 'mysql');
726// ... other providers and parameters
727app.init();
728// ... the rest of your Ravel app
729```
730
731#### Example Configuration
732
733*.ravelrc.json*
734```json
735{
736 "mysql options": {
737 "host": "localhost",
738 "port": 3306,
739 "user": "root",
740 "password": "a password",
741 "database": "mydatabase",
742 "idleTimeoutMillis": 5000,
743 "connectionLimit": 10
744 }
745}
746```
747
748#### List of Ravel `DatabaseProvider`s
749
750Ravel currently supports several `DatabaseProvider`s via external libraries.
751
752 - [`ravel-mysql-provider`](https://github.com/raveljs/ravel-mysql-provider)
753 - [`ravel-rethinkdb-provider`](https://github.com/raveljs/ravel-rethinkdb-provider)
754 - [`ravel-neo4j-provider`](https://github.com/raveljs/ravel-neo4j-provider)
755
756> 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!
757
758### Transaction-per-request
759> [<small>View API docs &#128366;</small>](http://raveljs.github.io/docs/latest/db/decorators/transaction.js.html)
760
761The `@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`.
762
763When 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.
764
765Connections 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).
766
767*resources/person-resource.js*
768```js
769const Resource = require('ravel').Resource;
770const transaction = Resource.transaction;
771
772class PersonResource extends Resource {
773 constructor (bodyParser, fs, custom) {
774 super('/person');
775 }
776
777 // maps to GET /person/:id
778 @transaction('mysql') // this is the name exposed by ravel-mysql-provider
779 async get (ctx) {
780 // TIP: Don't write complex logic here. Pass ctx.transaction into
781 // a Module function which returns a Promise! This example is
782 // just for demonstration purposes.
783 ctx.body = await new Promise((resolve, reject) => {
784 // ctx.transaction.mysql is a https://github.com/felixge/node-mysql connection
785 ctx.transaction.mysql.query('SELECT 1', (err, rows) => {
786 if (err) return reject(err);
787 resolve(rows);
788 });
789 });
790 }
791}
792module.exports = PersonResource;
793```
794
795### Scoped Transactions
796> [<small>View API docs &#128366;</small>](http://raveljs.github.io/docs/latest/core/module.js.html)
797
798Sometimes, 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:
799
800*modules/database-initializer.js*
801```js
802const Module = require('ravel').Module;
803const prelisten = Module.prelisten;
804
805class DatabaseInitializer extends Module {
806
807 @prelisten // trigger db init on application startup
808 doDbInit (ctx) {
809 const self = this;
810 // specify one or more providers to open connections to, or none
811 // to open connections to all known DatabaseProviders.
812 this.db.scoped('mysql', async function (ctx) {
813 // this async function behaves like koa middleware,
814 // so feel free to await on promises!
815 await self.createTables(ctx.transaction.mysql);
816 await self.insertRows(ctx.transaction.mysql);
817 // notice that this.transaction is identical to ctx.transaction
818 // from @transaction! It's just a hash of open, named connections
819 // to the DatabaseProviders specified.
820 }).catch((err) => {
821 self.log.error(err.stack);
822 process.exit(1); // in this case, we might want to kill our app if db init fails!
823 });
824 }
825
826 /**
827 * @returns {Promise}
828 */
829 createTables (mysqlConnection) { /* ... */ }
830
831 /**
832 * @returns {Promise}
833 */
834 insertRows (mysqlConnection) { /* ... */ }
835}
836
837module.exports = DatabaseInitializer;
838```
839
840### Authentication Providers
841> [<small>View API docs &#128366;</small>](http://raveljs.github.io/docs/latest/auth/authentication_provider.js.html)
842
843An `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):
844
845#### Example Setup
846
847*app.js*
848```javascript
849const app = new require('ravel')();
850const GitHubProvider = require('ravel-github-oauth2-provider');
851new GitHubProvider(app);
852// ... other providers and parameters
853app.init();
854// ... the rest of your Ravel app
855```
856
857#### Example Configuration
858
859*.ravelrc.json*
860```json
861{
862 "github auth callback url" : "http://localhost:8080",
863 "github auth path": "/auth/github",
864 "github auth callback path": "/auth/github/callback",
865 "github client id": "YOUR_CLIENT_ID",
866 "github client secret" : "YOUR_CLIENT_SECRET"
867}
868```
869
870You'll also need to implement an `@authconfig` module like this:
871
872*modules/authconfig.js*
873```js
874'use strict';
875
876const Ravel = require('ravel');
877const inject = Ravel.inject;
878const Module = Ravel.Module;
879const authconfig = Module.authconfig;
880
881@authconfig
882@inject('user-profiles')
883class AuthConfig extends Module {
884 constructor (userProfiles) {
885 this.userProfiles = userProfiles;
886 }
887 serializeUser (profile) {
888 // serialize profile to session using the id field
889 return Promise.resolve(profile.id);
890 }
891 deserializeUser (id) {
892 // retrieve profile from database using id from session
893 return this.userProfiles.getProfile(id); // a Promise
894 }
895 verify (providerName, ...args) {
896 // this method is roughly equivalent to the Passport verify callback, but
897 // supports multiple simultaneous AuthenticationProviders.
898 // providerName is the name of the provider which needs credentials verified
899 // args is an array containing credentials, such as username/password for
900 // verification against your database, or a profile and OAuth tokens. See
901 // specific AuthenticationProvider library READMEs for more information about
902 // how to implement this method.
903 }
904}
905
906module.exports = AuthConfig;
907```
908
909#### List of Ravel `AuthenticationProvider`s
910
911Ravel currently supports several `AuthenticationProvider`s via external libraries.
912
913 - [`ravel-github-oauth2-provider`](https://github.com/raveljs/ravel-github-oauth2-provider)
914 - [`ravel-google-oauth2-provider`](https://github.com/raveljs/ravel-google-oauth2-provider)
915
916> 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!
917
918### Authentication
919> [<small>View API docs &#128366;</small>](http://raveljs.github.io/docs/latest/auth/decorators/authenticated.js.html)
920
921Once 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:
922
923*Note: the @authenticated decorator works the same way on `Routes` and `Resource` classes/methods*
924```js
925const Routes = require('ravel').Routes;
926const mapping = Routes.mapping;
927const authenticated = Routes.authenticated;
928
929@authenticated // protect all endpoints in this Routes class
930class MyRoutes extends Routes {
931 constructor () {
932 super('/');
933 }
934
935 @authenticated({redirect: true}) // protect one endpoint specifically
936 @mapping(Routes.GET, 'app')
937 async handler (ctx) {
938 // will redirect to app.get('login route') if not signed in
939 }
940}
941```
942
943## Deployment and Scaling
944
945Ravel is designed for horizontal scaling, and helps you avoid common pitfalls when designing your node.js backend application. In particular:
946
947 - Session storage in [Redis](https://github.com/antirez/redis) is currently mandatory, ensuring that you can safely replicate your Ravel app safely
948 - The internal [koa](http://koajs.com/) application's `app.proxy` flag is set to `true`.
949 - 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.
950 - 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.
951
952It 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).
953
954Ravel 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.
955
956If 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.