Skip to content

Commit 8f6d961

Browse files
committed
Dont rebuild existing.
1 parent 8ea0110 commit 8f6d961

2 files changed

Lines changed: 23 additions & 1 deletion

File tree

standalone.js

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,17 @@
33
const fastJsonStringify = require('fast-json-stringify')
44

55
function SerializerSelector () {
6+
const cache = new Map()
67
return function buildSerializerFactory (externalSchemas, serializerOpts) {
78
const fjsOpts = Object.assign({}, serializerOpts, { schema: externalSchemas })
8-
return responseSchemaCompiler.bind(null, fjsOpts)
9+
return function cachedResponseSchemaCompiler (opts) {
10+
const key = JSON.stringify(opts.schema)
11+
const cached = cache.get(key)
12+
if (cached) return cached
13+
const result = responseSchemaCompiler(fjsOpts, opts)
14+
cache.set(key, result)
15+
return result
16+
}
917
}
1018
}
1119

test/plugin.test.js

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,20 @@ test('basic usage', t => {
3636
t.assert.equal(result, '{"name":"hello"}')
3737
})
3838

39+
test('cache hit for identical schemas across factories', t => {
40+
t.plan(2)
41+
const factory = FjsCompiler()
42+
43+
const compiler1 = factory(externalSchemas1, fastifyFjsOptionsDefault)
44+
const compiler2 = factory(externalSchemas1, fastifyFjsOptionsDefault)
45+
46+
const serialize1 = compiler1({ schema: sampleSchema })
47+
const serialize2 = compiler2({ schema: sampleSchema })
48+
49+
t.assert.equal(serialize1, serialize2, 'same serializer function returned from cache')
50+
t.assert.equal(serialize1({ name: 'cached' }), '{"name":"cached"}')
51+
})
52+
3953
test('fastify integration', async t => {
4054
const factory = FjsCompiler()
4155

0 commit comments

Comments
 (0)