Skip to content

Commit

Permalink
feat: synchronous plugin without callback (#265)
Browse files Browse the repository at this point in the history
* feat: synchronous plugin without callback

* fix README.md
  • Loading branch information
somnicattus authored Oct 15, 2024
1 parent 3e2e854 commit 3b9e210
Show file tree
Hide file tree
Showing 4 changed files with 36 additions and 4 deletions.
9 changes: 5 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -151,8 +151,6 @@ Loads one or more functions asynchronously.

The function **must** have the signature: `instance, options, done`

However, if the function returns a `Promise` (i.e. `async`), the above function signature is not required.

Plugin example:
```js
function plugin (server, opts, done) {
Expand All @@ -161,8 +159,11 @@ function plugin (server, opts, done) {

app.use(plugin)
```
`done` should be called only once, when your plugin is ready to go. Additional
calls to `done` are ignored.
`done` should be called only once, when your plugin is ready to go. Additional calls to `done` are ignored.

If your plugin is ready to go immediately after the function is evaluated, you can omit `done` from the signature.

If the function returns a `Promise` (i.e. `async`), the above function signature is not required.

`use` returns a thenable wrapped instance on which `use` is called, to support a chainable API that can also be awaited.

Expand Down
2 changes: 2 additions & 0 deletions lib/plugin.js
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,8 @@ Plugin.prototype.exec = function (server, callback) {
maybePromiseLike.then(
() => process.nextTick(done),
(e) => process.nextTick(done, e))
} else if (func.length < 3) {
done()
}
}

Expand Down
11 changes: 11 additions & 0 deletions test/load-plugin.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,17 @@ test('catch an error when loading a plugin with sync function', (t) => {
})
})

test('successfully load a plugin with sync function without done as a parameter', (t) => {
t.plan(1)
const app = boot({})

const plugin = new Plugin(fastq(app, app._loadPluginNextTick, 1), function (instance, opts) { }, false, 0)

app._loadPlugin(plugin, function (err) {
t.equal(err, undefined)
})
})

test('successfully load a plugin with async function', (t) => {
t.plan(1)
const app = boot({})
Expand Down
18 changes: 18 additions & 0 deletions test/no-done.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
'use strict'

const { test } = require('tap')
const boot = require('..')

test('not taking done does not throw error.', (t) => {
t.plan(2)

const app = boot()

app.use(noDone).ready((err) => {
t.notOk(err, 'no error')
})

function noDone (s, opts) {
t.pass('did not throw')
}
})

0 comments on commit 3b9e210

Please sign in to comment.