UNPKG

1.9 kBJavaScriptView Raw
1import { EventEmitter } from 'events';
2
3// Import a simple router that works anywhere.
4import Router from 'koa-router';
5
6// Custom errors for fun and profit.
7import RouteError from './routeError';
8
9import co from 'co';
10
11class App {
12 constructor (config) {
13 this.config = config;
14
15 // The router listens to web requests (or html5 history changes) and fires
16 // callbacks registered by plugins.
17 this.router = new Router();
18 this.emitter = new EventEmitter();
19
20 this.plugins = [];
21 }
22
23 // A nicer-looking way to load config values.
24 getConfig (c) {
25 return this.config[c];
26 }
27
28 // Accepts routes / history changes, and forwards on the req object and
29 // the response (a `defer` object). The last param, `function`, can be safely
30 // ignored - it's fired after handling.
31 route (ctx) {
32 this.emit('route:start', ctx);
33 var middleware = this.router.routes().call(ctx);
34 var app = this;
35
36 return co(function * () {
37 yield* middleware;
38 }).then(() => {
39 this.emit('route:end', ctx);
40 }, (err) => {
41 if(this.config.debug) {
42 console.log(err, err.stack);
43 }
44
45 return this.error(new RouteError(ctx.path), ctx, app);
46 }.bind(this));
47 }
48
49 registerPlugin (plugin) {
50 if (this.plugins.indexOf(plugin) === -1) {
51 this.plugins.push(plugin);
52 }
53 }
54
55 emit (...args) {
56 this.emitter.emit.apply(this, args);
57 }
58
59 on (...args) {
60 this.emitter.on.apply(this, args);
61 }
62
63 off (...args) {
64 this.emitter.off.apply(this, args);
65 }
66
67 error (err, ctx, app) {
68 var status = err.status || 500;
69 var message = err.message || 'Unkown error';
70
71 var reroute = '/' + status;
72 var url = '/' + status;
73
74 if (ctx.request.url !== url) {
75 ctx.redirect(status, url);
76 } else {
77 // Critical failure! The error page is erroring! Abandon all hope
78 console.log(err);
79 }
80 }
81}
82
83export default App;