1 |
|
2 |
|
3 |
|
4 | 'use strict';
|
5 |
|
6 | const Base = require('./Module');
|
7 | const StringHelper = require('../helper/StringHelper');
|
8 |
|
9 | module.exports = class Application extends Base {
|
10 |
|
11 | static getConstants () {
|
12 | return {
|
13 | DEFAULT_COMPONENTS: {
|
14 | 'bodyParser': {},
|
15 | 'formatter': {},
|
16 | 'router': {},
|
17 | 'urlManager': {},
|
18 | 'view': {}
|
19 | },
|
20 | EVENT_AFTER_START: 'afterStart'
|
21 | };
|
22 | }
|
23 |
|
24 | static getName () {
|
25 | return StringHelper.camelToId(StringHelper.trimEnd(this.name, 'Application'));
|
26 | }
|
27 |
|
28 | constructor (config) {
|
29 | super(config);
|
30 | this.mainEngine = this.createEngine();
|
31 | }
|
32 |
|
33 | async init () {
|
34 | await super.init();
|
35 | this.baseUrl = this.mountPath === '/' ? this.mountPath : `${this.mountPath}/`;
|
36 | }
|
37 |
|
38 | getRoute (url) {
|
39 | if (this._route === undefined) {
|
40 | this._route = this.mountPath === '/' ? '' : this.mountPath;
|
41 | }
|
42 | return url ? `${this._route}/${url}` : this._route;
|
43 | }
|
44 |
|
45 | createFullName () {
|
46 | return this.NAME;
|
47 | }
|
48 |
|
49 | createRelativeName () {
|
50 | return '';
|
51 | }
|
52 |
|
53 | start () {
|
54 | this.attachHandlers();
|
55 | return this.createServer();
|
56 | }
|
57 |
|
58 | afterStart () {
|
59 | return this.trigger(this.EVENT_AFTER_START);
|
60 | }
|
61 |
|
62 | attachHandlers () {
|
63 | super.attachHandlers();
|
64 | this.mainEngine.attachChild(this.mountPath, this.engine);
|
65 | }
|
66 |
|
67 | createServer () {
|
68 | return new Promise((resolve, reject) => {
|
69 | this.server = this.mainEngine.createServer().on('error', err => {
|
70 | this.log('error', 'Server error', err);
|
71 | reject(err);
|
72 | }).listen(this.getConfig('port'), ()=> {
|
73 | this.log('info', `Started ${this.fullName} as`, this.server.address());
|
74 | this.log('info', `Mounted ${this.fullName} as ${this.mountPath}`);
|
75 | this.afterStart().then(resolve);
|
76 | });
|
77 | });
|
78 | }
|
79 | };
|
80 | module.exports.init(); |
\ | No newline at end of file |