-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMiddleware.js
57 lines (47 loc) · 848 Bytes
/
Middleware.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
/**
* Class Middleware
* description 中间件
*/
class Middleware {
constructor() {
this.cache = []
this.options = null
}
use(fn) {
if (typeof fn !== "function") {
throw new Error("Middleware is must be a function! ")
}
this.cache.push(fn)
return this
}
next() {
if (this.middlewares && this.middlewares.length > 0) {
this.current = this.middlewares.shift()
this.current.call(this, this.options, this.next.bind(this))
}
}
run(options) {
this.middlewares = this.cache.map(fn => {
return fn
})
this.options = options
this.next()
}
}
var app = new Middleware()
app.use((options, next) => {
console.log("1")
next()
})
app.use((options, next) => {
console.log(options.name)
next()
})
app.use((options, next) => {
console.log(options.age)
next()
})
app.run({
name: "like",
age: "fuck"
})