diff --git a/SerializerManager.js b/SerializerManager.js index 892f4b0..306dc19 100644 --- a/SerializerManager.js +++ b/SerializerManager.js @@ -14,15 +14,21 @@ class Serializer { 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 } } } @@ -45,7 +51,8 @@ SerializerManager.expand = function (options, fallbackSerializer) { const serializers = options.serializers.map(c => new Serializer(c)) return new SerializerManager({ - serializers: serializers.concat(fallbackSerializer.serializers) + serializers: serializers.concat(fallbackSerializer.serializers), + cache: options.cache }) } diff --git a/index.js b/index.js index 6ec398e..5e7ef29 100644 --- a/index.js +++ b/index.js @@ -6,6 +6,9 @@ const SerializerManager = require('./SerializerManager') const FASTIFY_DEFAULT_SERIALIZE_MIME_TYPE = 'application/json' function acceptsSerializerPlugin (fastify, options, next) { + const serializerCache = {} + options.cache = serializerCache + const globalSerializerManager = SerializerManager.build(options) const defaultSerializer = globalSerializerManager.findSerializer([options.default]) @@ -17,6 +20,7 @@ function acceptsSerializerPlugin (fastify, options, next) { let serializer let type + reply.serializer.cache = serializerCache reply.serializer.serializerManager = SerializerManager.expand(reply.serializer, globalSerializerManager) const serializerManager = reply.serializer.serializerManager diff --git a/test/test.js b/test/test.js index e3ec9c5..c2c5bb2 100644 --- a/test/test.js +++ b/test/test.js @@ -365,3 +365,54 @@ test('serializer without conf', t => { }) }) }) + +test('serializer cache', t => { + t.plan(1) + + const fastify = Fastify() + + fastify.register(plugin, { + serializers: [ + { + regex: /^application\/cache$/, + serializer: (body) => body + } + ] + }) + + t.test('it shoud populate cache', t => { + t.plan(8) + + fastify.get('/request', function (req, reply) { + t.strictDeepEqual(Object.keys(reply.serializer.cache), ['application/cache']) + + reply.send('cache') + }) + + fastify.inject({ + method: 'GET', + url: '/request', + payload: {}, + headers: { + accept: 'application/cache' + } + }, (err, res) => { + t.error(err) + t.strictDeepEqual(res.headers['content-type'], 'application/cache') + t.strictDeepEqual(res.payload, 'cache') + }) + + fastify.inject({ + method: 'GET', + url: '/request', + payload: {}, + headers: { + accept: 'application/cache' + } + }, (err, res) => { + t.error(err) + t.strictDeepEqual(res.headers['content-type'], 'application/cache') + t.strictDeepEqual(res.payload, 'cache') + }) + }) +})