-
Notifications
You must be signed in to change notification settings - Fork 141
/
Copy pathconstrainer.js
172 lines (143 loc) · 5.61 KB
/
constrainer.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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
'use strict'
const acceptVersionStrategy = require('./strategies/accept-version')
const acceptHostStrategy = require('./strategies/accept-host')
const assert = require('node:assert')
class Constrainer {
constructor (customStrategies) {
this.strategies = {
version: acceptVersionStrategy,
host: acceptHostStrategy
}
this.strategiesInUse = new Set()
this.asyncStrategiesInUse = new Set()
// validate and optimize prototypes of given custom strategies
if (customStrategies) {
for (const strategy of Object.values(customStrategies)) {
this.addConstraintStrategy(strategy)
}
}
}
isStrategyUsed (strategyName) {
return this.strategiesInUse.has(strategyName) ||
this.asyncStrategiesInUse.has(strategyName)
}
hasConstraintStrategy (strategyName) {
const customConstraintStrategy = this.strategies[strategyName]
if (customConstraintStrategy !== undefined) {
return customConstraintStrategy.isCustom ||
this.isStrategyUsed(strategyName)
}
return false
}
addConstraintStrategy (strategy) {
assert(typeof strategy.name === 'string' && strategy.name !== '', 'strategy.name is required.')
assert(strategy.storage && typeof strategy.storage === 'function', 'strategy.storage function is required.')
assert(strategy.deriveConstraint && typeof strategy.deriveConstraint === 'function', 'strategy.deriveConstraint function is required.')
if (this.strategies[strategy.name] && this.strategies[strategy.name].isCustom) {
throw new Error(`There already exists a custom constraint with the name ${strategy.name}.`)
}
if (this.isStrategyUsed(strategy.name)) {
throw new Error(`There already exists a route with ${strategy.name} constraint.`)
}
strategy.isCustom = true
strategy.isAsync = strategy.deriveConstraint.length === 3
this.strategies[strategy.name] = strategy
if (strategy.mustMatchWhenDerived) {
this.noteUsage({ [strategy.name]: strategy })
}
}
deriveConstraints (req, ctx, done) {
const constraints = this.deriveSyncConstraints(req, ctx)
if (done === undefined) {
return constraints
}
this.deriveAsyncConstraints(constraints, req, ctx, done)
}
deriveSyncConstraints (req, ctx) {
return undefined
}
// When new constraints start getting used, we need to rebuild the deriver to derive them. Do so if we see novel constraints used.
noteUsage (constraints) {
if (constraints) {
const beforeSize = this.strategiesInUse.size
for (const key in constraints) {
const strategy = this.strategies[key]
if (strategy.isAsync) {
this.asyncStrategiesInUse.add(key)
} else {
this.strategiesInUse.add(key)
}
}
if (beforeSize !== this.strategiesInUse.size) {
this._buildDeriveConstraints()
}
}
}
newStoreForConstraint (constraint) {
if (!this.strategies[constraint]) {
throw new Error(`No strategy registered for constraint key ${constraint}`)
}
return this.strategies[constraint].storage()
}
validateConstraints (constraints) {
for (const key in constraints) {
const value = constraints[key]
if (typeof value === 'undefined') {
throw new Error('Can\'t pass an undefined constraint value, must pass null or no key at all')
}
const strategy = this.strategies[key]
if (!strategy) {
throw new Error(`No strategy registered for constraint key ${key}`)
}
if (strategy.validate) {
strategy.validate(value)
}
}
}
deriveAsyncConstraints (constraints, req, ctx, done) {
let asyncConstraintsCount = this.asyncStrategiesInUse.size
if (asyncConstraintsCount === 0) {
done(null, constraints)
return
}
constraints = constraints || {}
for (const key of this.asyncStrategiesInUse) {
const strategy = this.strategies[key]
strategy.deriveConstraint(req, ctx, (err, constraintValue) => {
if (err !== null) {
done(err)
return
}
constraints[key] = constraintValue
if (--asyncConstraintsCount === 0) {
done(null, constraints)
}
})
}
}
// Optimization: build a fast function for deriving the constraints for all the strategies at once. We inline the definitions of the version constraint and the host constraint for performance.
// If no constraining strategies are in use (no routes constrain on host, or version, or any custom strategies) then we don't need to derive constraints for each route match, so don't do anything special, and just return undefined
// This allows us to not allocate an object to hold constraint values if no constraints are defined.
_buildDeriveConstraints () {
if (this.strategiesInUse.size === 0) return
const lines = ['return {']
for (const key of this.strategiesInUse) {
const strategy = this.strategies[key]
// Optimization: inline the derivation for the common built in constraints
if (!strategy.isCustom) {
if (key === 'version') {
lines.push(' version: req.headers[\'accept-version\'],')
} else if (key === 'host') {
lines.push(' host: req.headers.host || req.headers[\':authority\'],')
} else {
throw new Error('unknown non-custom strategy for compiling constraint derivation function')
}
} else {
lines.push(` ${strategy.name}: this.strategies.${key}.deriveConstraint(req, ctx),`)
}
}
lines.push('}')
this.deriveSyncConstraints = new Function('req', 'ctx', lines.join('\n')).bind(this) // eslint-disable-line
}
}
module.exports = Constrainer