-
-
Notifications
You must be signed in to change notification settings - Fork 42
/
index.js
70 lines (53 loc) · 1.77 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
'use strict'
const semver = require('semver')
const console = require('console')
const fpStackTracePattern = new RegExp('at\\s{1}(?:.*\\.)?plugin\\s{1}.*\\n\\s*(.*)')
const fileNamePattern = new RegExp('(?:\\/|\\\\)(\\w*(\\.\\w*)*)\\..*')
function plugin (fn, options = {}) {
if (typeof fn !== 'function') {
throw new TypeError(`fastify-plugin expects a function, instead got a '${typeof fn}'`)
}
fn[Symbol.for('skip-override')] = true
if (typeof options === 'string') {
checkVersion(options)
options = {}
}
if (typeof options !== 'object' || Array.isArray(options) || options === null) {
throw new TypeError('The options object should be an object')
}
if (!options.name) {
options.name = checkName(fn)
}
fn[Symbol.for('fastify.display-name')] = options.name
if (options.fastify) {
checkVersion(options.fastify)
delete options.fastify
}
fn[Symbol.for('plugin-meta')] = options
return fn
}
function checkName (fn) {
if (fn.name.length > 0) return fn.name
try {
throw new Error('anonymous function')
} catch (e) {
const stack = e.stack
let m = stack.match(fpStackTracePattern)
return m ? m[1].match(fileNamePattern)[1] : 'anonymous'
}
}
function checkVersion (version) {
if (typeof version !== 'string') {
throw new TypeError(`fastify-plugin expects a version string, instead got '${typeof version}'`)
}
var fastifyVersion
try {
fastifyVersion = require('fastify/package.json').version.replace(/-rc\.\d+/, '')
} catch (_) {
console.info('fastify not found, proceeding anyway')
}
if (fastifyVersion && !semver.satisfies(fastifyVersion, version)) {
throw new Error(`fastify-plugin - expected '${version}' fastify version, '${fastifyVersion}' is installed`)
}
}
module.exports = plugin