UNPKG

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