UNPKG

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