1 | import { EventEmitter } from 'events';
|
2 |
|
3 |
|
4 | import Router from 'koa-router';
|
5 |
|
6 |
|
7 | import RouteError from './routeError';
|
8 |
|
9 | import co from 'co';
|
10 |
|
11 | class App {
|
12 | constructor (config) {
|
13 | this.config = config;
|
14 |
|
15 |
|
16 |
|
17 | this.router = new Router();
|
18 | this.emitter = new EventEmitter();
|
19 |
|
20 | this.plugins = [];
|
21 | }
|
22 |
|
23 |
|
24 | getConfig (c) {
|
25 | return this.config[c];
|
26 | }
|
27 |
|
28 |
|
29 |
|
30 |
|
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 |
|
88 | console.log(err);
|
89 | }
|
90 | }
|
91 | }
|
92 |
|
93 | export default App;
|