Skip to content

Commit

Permalink
fn.default check for transpiled modules (#61)
Browse files Browse the repository at this point in the history
* fn.default check for transpiled modules

More info in issue #60

* lint fix (oops)

* Unit test for ECMAScript module

* Apply suggestions from code review

Co-Authored-By: nurdism <craigbett@gmail.com>

* Apply suggestions from @delvedor

* Apply suggestions from @Ethan-Arrowood
  • Loading branch information
nurdism authored and mcollina committed Feb 6, 2019
1 parent 31708bb commit caff3e9
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 1 deletion.
2 changes: 1 addition & 1 deletion fastify-plugin.d.ts
Expand Up @@ -12,7 +12,7 @@ import * as fastify from 'fastify';
* @param next The `next` callback is not available when using `async`/`await`. If you do invoke a `next` callback in this situation unexpected behavior may occur.
*/
declare function fastifyPlugin<HttpServer, HttpRequest, HttpResponse, T>(
fn: fastify.Plugin<HttpServer, HttpRequest, HttpResponse, T>,
fn: fastify.Plugin<HttpServer, HttpRequest, HttpResponse, T> | { default: fastify.Plugin<HttpServer, HttpRequest, HttpResponse, T> },
options?: fastifyPlugin.PluginOptions | string,
next?: fastifyPlugin.nextCallback
): fastify.Plugin<HttpServer, HttpRequest, HttpResponse, T>;
Expand Down
4 changes: 4 additions & 0 deletions index.js
Expand Up @@ -5,6 +5,10 @@ const console = require('console')
const extractPluginName = require('./stackParser')

function plugin (fn, options = {}) {
if (typeof fn.default !== 'undefined') { // Support for 'export default' behaviour in transpiled ECMAScript module
fn = fn.default
}

if (typeof fn !== 'function') {
throw new TypeError(`fastify-plugin expects a function, instead got a '${typeof fn}'`)
}
Expand Down
15 changes: 15 additions & 0 deletions test/test.js
Expand Up @@ -22,6 +22,21 @@ test('should return the function with the skip-override Symbol', t => {
t.ok(plugin[Symbol.for('skip-override')])
})

test('should support "default" function from babel module', t => {
t.plan(1)

const plugin = {
default: () => {}
}

try {
fp(plugin)
t.pass()
} catch (e) {
t.is(e.message, 'fastify-plugin expects a function, instead got a \'object\'')
}
})

test('should throw if the plugin is not a function', t => {
t.plan(1)

Expand Down

0 comments on commit caff3e9

Please sign in to comment.