-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapplication.js
107 lines (94 loc) · 2.67 KB
/
application.js
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
/**
* Created by wlhuang on 2017/1/9.
*/
const coo = require('./lib/coo')
const Log = require('./lib/log')
const config = require('./config')
const path = require('path')
const http = require('http')
const https = require('https')
const context = require('./wrapper/context')
const Request = require('./wrapper/request')
const Response = require('./wrapper/response')
const handler = require('./lib/handleStatic')
const session = require('./session')
const log = new Log(config.level)
/**
* simplify koa
* 上下文
* @constructor
*/
function Application() {
this.middleware = []
this.routes = []
this.request = {}
this.response = {}
this.sessionManager = new session.SessionManage(config.cookie.timeout)
}
var App = Application.prototype
/**
* set static resource
*/
App.setStatic = function(path) {
this.staticPath = path
}
/**
* start ---------------->
* <---------------- send
* @param next
*/
function *send(next) {
log.info('---------------------------->')
yield *next
log.info('<----------------------------')
}
App.handleSession = function () {
var sessionId = this.request.cookie[config.cookie.key],
session
if(sessionId && (session = this.sessionManager.get(sessionId))) {
if(session.isTimeout) {
this.sessionManager.remove(sessionId)
session = this.sessionManager.generate(this.response)
} else {
session.updateTime()
}
} else {
session = this.sessionManager.generate(this.response)
}
this.request.session = session
}
App.compose = function(middleware, context) {
return coo(function *() {
var refer = (function *() {})(),
len = middleware.length
while(len--) {
refer = middleware[len].call(context, refer)
}
yield *refer
})
}
App.use = function(generator) {
this.middleware.push(generator)
}
App.dispatch = function() {
var next = this.compose.call(this, [send].concat(this.middleware), this),
ext = null
return function(request, response) {
this.request = Request(request)
this.response = Response(response)
if(ext = path.extname(this.request.path).slice(1)) {
handler(this.response, this.staticPath + this.request.path, ext)
} else {
this.handleSession()
next.call(this)
}
}.bind(this)
}
App.listen = function(port, https) {
var server = https ? https.createServer(this.dispatch()) : http.createServer(this.dispatch())
server.listen(port, function() {
log.info('Server listening at Port %s.', port)
})
}
Object.assign(App, context)
module.exports = Application