UNPKG

2.29 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.mainEngine = this.createEngine();
26 }
27
28 getBaseName () {
29 if (!this._baseName) {
30 this._baseName = StringHelper.camelToId(StringHelper.trimEnd(this.constructor.name, 'Application'));
31 }
32 return this._baseName;
33 }
34
35 async init () {
36 await super.init();
37 this.baseUrl = this.mountPath === '/' ? this.mountPath : `${this.mountPath}/`;
38 }
39
40 getRoute (url) {
41 if (this._route === undefined) {
42 this._route = this.mountPath === '/' ? '' : this.mountPath;
43 }
44 return url ? `${this._route}/${url}` : this._route;
45 }
46
47 createFullName () {
48 return this.getBaseName();
49 }
50
51 createRelativeName () {
52 return '';
53 }
54
55 start () {
56 this.attachHandlers();
57 return this.createServer();
58 }
59
60 afterStart () {
61 return this.trigger(this.EVENT_AFTER_START);
62 }
63
64 attachHandlers () {
65 super.attachHandlers();
66 this.mainEngine.attachChild(this.mountPath, this.engine);
67 }
68
69 createServer () {
70 return new Promise((resolve, reject) => {
71 this.server = this.mainEngine.createServer().on('error', err => {
72 this.log('error', 'Server error', err);
73 reject(err);
74 }).listen(this.getConfig('port'), ()=> {
75 this.log('info', `Started ${this.fullName} as`, this.server.address());
76 this.log('info', `Mounted ${this.fullName} as ${this.mountPath}`);
77 this.afterStart().then(resolve);
78 });
79 });
80 }
81};
82module.exports.init();
83
84const StringHelper = require('../helper/StringHelper');
\No newline at end of file