strong-tie/inbound-calls
0
1'use strict'2 3const getPluginName = require('./lib/getPluginName')4const toCamelCase = require('./lib/toCamelCase')5 6let count = 07 8function plugin (fn, options = {}) {9 let autoName = false10 11 if (fn.default !== undefined) {12 // Support for 'export default' behaviour in transpiled ECMAScript module13 fn = fn.default14 }15 16 if (typeof fn !== 'function') {17 throw new TypeError(18 `fastify-plugin expects a function, instead got a '${typeof fn}'`19 )20 }21 22 if (typeof options === 'string') {23 options = {24 fastify: options25 }26 }27 28 if (29 typeof options !== 'object' ||30 Array.isArray(options) ||31 options === null32 ) {33 throw new TypeError('The options object should be an object')34 }35 36 if (options.fastify !== undefined && typeof options.fastify !== 'string') {37 throw new TypeError(`fastify-plugin expects a version string, instead got '${typeof options.fastify}'`)38 }39 40 if (!options.name) {41 autoName = true42 options.name = getPluginName(fn) + '-auto-' + count++43 }44 45 fn[Symbol.for('skip-override')] = options.encapsulate !== true46 fn[Symbol.for('fastify.display-name')] = options.name47 fn[Symbol.for('plugin-meta')] = options48 49 // Faux modules support50 if (!fn.default) {51 fn.default = fn52 }53 54 // TypeScript support for named imports55 // See https://github.com/fastify/fastify/issues/2404 for more details56 // The type definitions would have to be update to match this.57 const camelCase = toCamelCase(options.name)58 if (!autoName && !fn[camelCase]) {59 fn[camelCase] = fn60 }61 62 return fn63}64 65module.exports = plugin66module.exports.default = plugin67module.exports.fastifyPlugin = plugin68 