/
application.ts
86 lines (74 loc) · 1.75 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 Koa from 'koa'
import { createServer, Server } from 'http'
import { LoggerNameSpace, NOT_FOUND_APPLICATION_CONFIG } from '@/constants'
import { ApplicationLogger, createLogger } from './logger'
import { useMiddlewares } from './core/middlewares/useMiddlewares'
import { loggerConfig } from '@/config'
import { initRouter } from './router'
import type { AppContext, Config } from '@/types'
/**
* 应用
*/
export class Application {
/**
* koa实例
*/
public app: Koa
/**
* 服务配置
*/
public config: Config.Application
/**
* 服务实例
*/
public server: Server
/**
* 日志实例
*/
public logger: ApplicationLogger
/**
* 构造函数
* @param config
*/
constructor(config: Config.Application) {
if (!config) throw TypeError(NOT_FOUND_APPLICATION_CONFIG)
this.config = config
this.app = new Koa()
this.server = createServer(this.app.callback())
this.logger = createLogger(loggerConfig)
this.useMiddleware()
this.mountRouter()
}
/**
* 挂载中间件
*/
useMiddleware() {
// 做一些对象的挂载方便后续使用
this.app.use(async (ctx: AppContext, next) => {
ctx.$ = ctx.server = this
ctx.logger = this.logger
await next()
})
// 挂载中间件
useMiddlewares(this.app)
}
/**
* 启动服务
*/
start() {
const { host, port } = this.config
try {
this.server.listen(port, host, () => {
this.logger.info(LoggerNameSpace.App, `服务已运行在http://${host}:${port}`, '✔ ')
})
} catch (error) {
this.logger.fatal(LoggerNameSpace.App, `服务http://${host}:${port}启动失败!`, error)
}
}
/**
* 挂载路由
*/
mountRouter() {
initRouter(this)
}
}