-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapplication.ts
86 lines (66 loc) · 2.8 KB
/
application.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import * as dotenv from 'dotenv';
import * as nodePath from 'path';
import * as cluster from 'cluster';
import * as os from 'os';
import Autoloader from './core/autoloader';
import Container from './core/container';
import ApplicationConfig from './config/application-config';
import DatabaseService from './service/database';
import I18nService from './service/i18n';
import MailService from './service/mail';
import HTTPServerService from './service/http-server';
import FileSystemUtil from './util/file-system';
import ContextConfig from './config/context-config';
import SMTPServerService from './service/smtp-server';
// kill process on unhandled promise rejection
process.on('unhandledRejection', err => {
throw err;
});
export default class Application {
private paths: string[];
private autoloader: Autoloader;
constructor(paths: string[] = [process.cwd()]) {
this.paths = paths;
const pathToDotEnv = nodePath.join(process.cwd(), '.env.' + String(process.env.NODE_ENV).toLowerCase());
if (!FileSystemUtil.isFileSync(pathToDotEnv)) {
throw new Error(pathToDotEnv + ' does not exists.');
}
dotenv.config({ path: pathToDotEnv });
this.autoloader = new Autoloader();
}
public async start(): Promise<void> {
await this.autoloader.load(this.paths);
const applicationConfig = await Container.get<ApplicationConfig>(ApplicationConfig);
applicationConfig.paths = this.paths;
if (cluster.isMaster && applicationConfig.cluster) {
for (const cpu of os.cpus()) {
cluster.fork();
}
return;
}
const contextConfig = await Container.get<ContextConfig>(ContextConfig);
const database = await Container.get<DatabaseService>(DatabaseService);
await database.start();
if (contextConfig.isTest()) {
const smtp = await Container.get<SMTPServerService>(SMTPServerService);
await smtp.start();
}
const i18n = await Container.get<I18nService>(I18nService);
await i18n.start();
const mail = await Container.get<MailService>(MailService);
await mail.start();
const server = await Container.get<HTTPServerService>(HTTPServerService);
await server.start();
}
public async stop(): Promise<void> {
const server = await Container.get<HTTPServerService>(HTTPServerService);
await server.stop();
const contextConfig = await Container.get<ContextConfig>(ContextConfig);
if (contextConfig.isTest()) {
const smtp = await Container.get<SMTPServerService>(SMTPServerService);
await smtp.stop();
}
const database = await Container.get<DatabaseService>(DatabaseService);
await database.stop();
}
}