forked from fastify/middie
-
Notifications
You must be signed in to change notification settings - Fork 0
/
middie.js
96 lines (82 loc) · 2.04 KB
/
middie.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
'use strict'
const reusify = require('reusify')
const pathMatch = require('pathname-match')
function middie (complete) {
var middlewares = []
var pool = reusify(Holder)
return {
use,
run
}
function use (url, f) {
if (typeof url === 'function') {
f = url
url = null
}
middlewares.push({
path: url,
fn: f,
wildcard: hasWildcard(url)
})
return this
}
function run (req, res) {
if (!middlewares.length) {
complete(null, req, res)
return
}
const holder = pool.get()
holder.req = req
holder.res = res
holder.url = pathMatch(req.url)
holder.done()
}
function Holder () {
this.next = null
this.req = null
this.res = null
this.url = null
this.i = 0
var that = this
this.done = function (err) {
const req = that.req
const res = that.res
const url = that.url
const i = that.i++
if (err || middlewares.length === i) {
complete(err, req, res)
that.req = null
that.res = null
that.i = 0
pool.release(that)
} else {
const middleware = middlewares[i]
const fn = middleware.fn
if (!middleware.path) {
fn(req, res, that.done)
} else if (middleware.wildcard && pathMatchWildcard(url, middleware.path)) {
fn(req, res, that.done)
} else if (middleware.path === url || (typeof middleware.path !== 'string' && middleware.path.indexOf(url) > -1)) {
fn(req, res, that.done)
} else {
that.done()
}
}
}
}
}
function hasWildcard (url) {
return typeof url === 'string' && url.length > 2 && url.charCodeAt(url.length - 1) === 42 /* * */ && url.charCodeAt(url.length - 2) === 47 /* / */
}
function pathMatchWildcard (url, wildcardUrl) {
if (url.length < wildcardUrl.length) {
return false
}
for (var i = 0; i < wildcardUrl.length - 2; i++) {
if (url.charCodeAt(i) !== wildcardUrl.charCodeAt(i)) {
return false
}
}
return true
}
module.exports = middie