-
Notifications
You must be signed in to change notification settings - Fork 11
/
SerializerManager.js
59 lines (47 loc) · 1.39 KB
/
SerializerManager.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
'use strict'
class Serializer {
constructor (configuration) {
this.regex = configuration.regex
this.serializeFunction = configuration.serializer
}
isAble (type) {
return this.regex.test(type)
}
}
class SerializerManager {
constructor (configuration) {
this.serializers = configuration.serializers
this.cache = configuration.cache
}
findSerializer (types) {
const cacheValue = this.cache[types]
if (cacheValue) return cacheValue
for (let i = 0; i < types.length; i++) {
const type = types[i]
for (let j = 0; j < this.serializers.length; j++) {
const serializer = this.serializers[j]
if (serializer.isAble(type)) {
this.cache[types] = { serializer, type }
return { serializer, type }
}
}
}
return {}
}
getSupportedTypes () {
return this.serializers.map(s => s.regex)
}
}
SerializerManager.build = function (options) {
options.serializers = options.serializers || []
return SerializerManager.expand(options, { serializers: [] })
}
SerializerManager.expand = function (options, fallbackSerializer) {
options.serializers = options.serializers || []
const serializers = options.serializers.map(c => new Serializer(c))
return new SerializerManager({
serializers: serializers.concat(fallbackSerializer.serializers),
cache: options.cache
})
}
module.exports = SerializerManager