UNPKG

2.69 kBJavaScriptView Raw
1'use strict'
2
3const {
4 kAvvioBoot,
5 kChildren,
6 kRoutePrefix,
7 kLogLevel,
8 kLogSerializers,
9 kHooks,
10 kSchemas,
11 kContentTypeParser,
12 kReply,
13 kRequest,
14 kFourOhFour,
15 kPluginNameChain
16} = require('./symbols.js')
17
18const Reply = require('./reply')
19const Request = require('./request')
20const ContentTypeParser = require('./contentTypeParser')
21const { buildHooks } = require('./hooks')
22const { buildSchemas } = require('./schemas')
23const pluginUtils = require('./pluginUtils')
24
25// Function that runs the encapsulation magic.
26// Everything that need to be encapsulated must be handled in this function.
27module.exports = function override (old, fn, opts) {
28 const shouldSkipOverride = pluginUtils.registerPlugin.call(old, fn)
29
30 if (shouldSkipOverride) {
31 // after every plugin registration we will enter a new name
32 old[kPluginNameChain].push(pluginUtils.getDisplayName(fn))
33 return old
34 }
35
36 const instance = Object.create(old)
37 old[kChildren].push(instance)
38 instance.ready = old[kAvvioBoot].bind(instance)
39 instance[kChildren] = []
40 instance[kReply] = Reply.buildReply(instance[kReply])
41 instance[kRequest] = Request.buildRequest(instance[kRequest])
42 instance[kContentTypeParser] = ContentTypeParser.helpers.buildContentTypeParser(instance[kContentTypeParser])
43 instance[kHooks] = buildHooks(instance[kHooks])
44 instance[kRoutePrefix] = buildRoutePrefix(instance[kRoutePrefix], opts.prefix)
45 instance[kLogLevel] = opts.logLevel || instance[kLogLevel]
46 instance[kSchemas] = buildSchemas(old[kSchemas])
47 instance.getSchema = instance[kSchemas].getSchema.bind(instance[kSchemas])
48 instance.getSchemas = instance[kSchemas].getSchemas.bind(instance[kSchemas])
49 instance[pluginUtils.registeredPlugins] = Object.create(instance[pluginUtils.registeredPlugins])
50 instance[kPluginNameChain] = [pluginUtils.getPluginName(fn) || pluginUtils.getFuncPreview(fn)]
51
52 if (instance[kLogSerializers] || opts.logSerializers) {
53 instance[kLogSerializers] = Object.assign(Object.create(instance[kLogSerializers]), opts.logSerializers)
54 }
55
56 if (opts.prefix) {
57 instance[kFourOhFour].arrange404(instance)
58 }
59
60 for (const hook of instance[kHooks].onRegister) hook.call(this, instance, opts)
61
62 return instance
63}
64
65function buildRoutePrefix (instancePrefix, pluginPrefix) {
66 if (!pluginPrefix) {
67 return instancePrefix
68 }
69
70 // Ensure that there is a '/' between the prefixes
71 if (instancePrefix.endsWith('/') && pluginPrefix[0] === '/') {
72 // Remove the extra '/' to avoid: '/first//second'
73 pluginPrefix = pluginPrefix.slice(1)
74 } else if (pluginPrefix[0] !== '/') {
75 pluginPrefix = '/' + pluginPrefix
76 }
77
78 return instancePrefix + pluginPrefix
79}