UNPKG

2.15 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 var match = this.router.match(ctx.path).filter((r) => {
37 return ~r.methods.indexOf(ctx.method);
38 }).length;
39
40 if (!match) {
41 return function * () {
42 app.error(new RouteError(ctx.path), ctx, app);
43 }
44 }
45
46 return co(function * () {
47 yield* middleware;
48 }).then(() => {
49 this.emit('route:end', ctx);
50 }, (err) => {
51 if(this.config.debug) {
52 console.log(err, err.stack);
53 }
54
55 this.error(err, ctx, app);
56 }.bind(this));
57 }
58
59 registerPlugin (plugin) {
60 if (this.plugins.indexOf(plugin) === -1) {
61 this.plugins.push(plugin);
62 }
63 }
64
65 emit (...args) {
66 this.emitter.emit.apply(this.emitter, args);
67 }
68
69 on (...args) {
70 this.emitter.on.apply(this.emitter, args);
71 }
72
73 off (...args) {
74 this.emitter.removeListener.apply(this.emitter, args);
75 }
76
77 error (err, ctx, app) {
78 var status = err.status || 500;
79 var message = err.message || 'Unkown error';
80
81 var reroute = '/' + status;
82 var url = '/' + status;
83
84 if (ctx.request.url !== url) {
85 ctx.redirect(reroute, url);
86 } else {
87 // Critical failure! The error page is erroring! Abandon all hope
88 console.log(err);
89 }
90 }
91}
92
93export default App;