1 | 'use strict'
|
2 |
|
3 | const {
|
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 |
|
18 | const Reply = require('./reply')
|
19 | const Request = require('./request')
|
20 | const ContentTypeParser = require('./contentTypeParser')
|
21 | const { buildHooks } = require('./hooks')
|
22 | const { buildSchemas } = require('./schemas')
|
23 | const pluginUtils = require('./pluginUtils')
|
24 |
|
25 |
|
26 |
|
27 | module.exports = function override (old, fn, opts) {
|
28 | const shouldSkipOverride = pluginUtils.registerPlugin.call(old, fn)
|
29 |
|
30 | if (shouldSkipOverride) {
|
31 |
|
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 |
|
65 | function buildRoutePrefix (instancePrefix, pluginPrefix) {
|
66 | if (!pluginPrefix) {
|
67 | return instancePrefix
|
68 | }
|
69 |
|
70 |
|
71 | if (instancePrefix.endsWith('/') && pluginPrefix[0] === '/') {
|
72 |
|
73 | pluginPrefix = pluginPrefix.slice(1)
|
74 | } else if (pluginPrefix[0] !== '/') {
|
75 | pluginPrefix = '/' + pluginPrefix
|
76 | }
|
77 |
|
78 | return instancePrefix + pluginPrefix
|
79 | }
|