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 | 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 |
|
78 | console.log(err);
|
79 | }
|
80 | }
|
81 | }
|
82 |
|
83 | export default App;
|