UNPKG

2.77 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 getPluginName (func) {
15 // let's see if this is a file, and in that case use that
16 // this is common for plugins
17 const cache = require.cache
18 const keys = Object.keys(cache)
19
20 for (var i = 0; i < keys.length; i++) {
21 if (cache[keys[i]].exports === func) {
22 return keys[i]
23 }
24 }
25
26 // if not maybe it's a named function, so use that
27 if (func.name) {
28 return func.name
29 }
30
31 return null
32}
33
34function getFuncPreview (func) {
35 // takes the first two lines of the function if nothing else works
36 return func.toString().split('\n').slice(0, 2).map(s => s.trim()).join(' -- ')
37}
38
39function getDisplayName (fn) {
40 return fn[Symbol.for('fastify.display-name')]
41}
42
43function shouldSkipOverride (fn) {
44 return !!fn[Symbol.for('skip-override')]
45}
46
47function checkDependencies (fn) {
48 const meta = getMeta(fn)
49 if (!meta) return
50
51 const dependencies = meta.dependencies
52 if (!dependencies) return
53 assert(Array.isArray(dependencies), 'The dependencies should be an array of strings')
54
55 dependencies.forEach(dependency => {
56 assert(
57 this[registeredPlugins].indexOf(dependency) > -1,
58 `The dependency '${dependency}' of plugin '${meta.name}' is not registered`
59 )
60 })
61}
62
63function checkDecorators (fn) {
64 const meta = getMeta(fn)
65 if (!meta) return
66
67 const decorators = meta.decorators
68 if (!decorators) return
69
70 if (decorators.fastify) _checkDecorators.call(this, 'Fastify', decorators.fastify)
71 if (decorators.reply) _checkDecorators.call(this[kReply], 'Reply', decorators.reply)
72 if (decorators.request) _checkDecorators.call(this[kRequest], 'Request', decorators.request)
73}
74
75function _checkDecorators (instance, decorators) {
76 assert(Array.isArray(decorators), 'The decorators should be an array of strings')
77
78 decorators.forEach(decorator => {
79 assert(
80 instance === 'Fastify' ? decorator in this : decorator in this.prototype,
81 `The decorator '${decorator}' is not present in ${instance}`
82 )
83 })
84}
85
86function registerPluginName (fn) {
87 const meta = getMeta(fn)
88 if (!meta) return
89
90 const name = meta.name
91 if (!name) return
92 this[registeredPlugins].push(name)
93}
94
95function registerPlugin (fn) {
96 registerPluginName.call(this, fn)
97 checkDecorators.call(this, fn)
98 checkDependencies.call(this, fn)
99 return shouldSkipOverride(fn)
100}
101
102module.exports = {
103 getPluginName,
104 getFuncPreview,
105 registeredPlugins,
106 getDisplayName,
107 registerPlugin
108}
109
110module.exports[Symbol.for('internals')] = {
111 shouldSkipOverride,
112 getMeta,
113 checkDecorators,
114 checkDependencies
115}