UNPKG

2.03 kBJavaScriptView Raw
1'use strict'
2
3const assert = require('assert')
4const registeredPlugins = Symbol.for('registered-plugin')
5const {
6 kReply,
7 kRequest
8} = require('./symbols.js')
9
10function getMeta (fn) {
11 return fn[Symbol.for('plugin-meta')]
12}
13
14function shouldSkipOverride (fn) {
15 return !!fn[Symbol.for('skip-override')]
16}
17
18function checkDependencies (fn) {
19 const meta = getMeta(fn)
20 if (!meta) return
21
22 const dependencies = meta.dependencies
23 if (!dependencies) return
24 assert(Array.isArray(dependencies), 'The dependencies should be an array of strings')
25
26 dependencies.forEach(dependency => {
27 assert(
28 this[registeredPlugins].indexOf(dependency) > -1,
29 `The dependency '${dependency}' of plugin '${meta.name}' is not registered`
30 )
31 })
32}
33
34function checkDecorators (fn) {
35 const meta = getMeta(fn)
36 if (!meta) return
37
38 const decorators = meta.decorators
39 if (!decorators) return
40
41 if (decorators.fastify) _checkDecorators.call(this, 'Fastify', decorators.fastify)
42 if (decorators.reply) _checkDecorators.call(this[kReply], 'Reply', decorators.reply)
43 if (decorators.request) _checkDecorators.call(this[kRequest], 'Request', decorators.request)
44}
45
46function _checkDecorators (instance, decorators) {
47 assert(Array.isArray(decorators), 'The decorators should be an array of strings')
48
49 decorators.forEach(decorator => {
50 assert(
51 instance === 'Fastify' ? decorator in this : decorator in this.prototype,
52 `The decorator '${decorator}' is not present in ${instance}`
53 )
54 })
55}
56
57function registerPluginName (fn) {
58 const meta = getMeta(fn)
59 if (!meta) return
60
61 const name = meta.name
62 if (!name) return
63 this[registeredPlugins].push(name)
64}
65
66function registerPlugin (fn) {
67 registerPluginName.call(this, fn)
68 checkDecorators.call(this, fn)
69 checkDependencies.call(this, fn)
70 return shouldSkipOverride(fn)
71}
72
73module.exports = {
74 registeredPlugins,
75 registerPlugin
76}
77
78module.exports[Symbol.for('internals')] = {
79 shouldSkipOverride,
80 getMeta,
81 checkDecorators,
82 checkDependencies
83}