smartiniOnGitHub/fastify-webhook

Unable to reference (directly) handler functions exposed by the plugin

Closed this issue · 6 comments

In the plugin I expose some generic functions that could be useful to debug webhooks.
The default handler function works, but when I try to use one of other handlers (loggerWebhookHandler, echoWebhookHandler) from consumers of the plugin (for example in tests), it seems that they are not found (so the default handler is always used).
All this because the plugin is exported but wrapped by 'fastify-plugin' (ok).
For example (extract from tests, currently it's latest which is failing):

test('custom options for webhook (using plugin echoWebhookHandler and optional input content type and body) does not return an error, but a good response (200) and some content', (t) => {
  t.plan(5)
  const fastify = Fastify()
  const webhookPlugin = require('../')
  fastify.register(webhookPlugin, {
    'url': '/custom-webhook',
    'handler': webhookPlugin.echoWebhookHandler // get a reference to another handler
// TODO: probably this is the real problem, it's not found, so default handler is used instead ...
  })

  fastify.listen(0, (err) => {
    fastify.server.unref()
    t.error(err)
    const port = fastify.server.address().port
    const sampleData = '{"payload":"test"}'

    request({
      method: 'POST',
      uri: `http://localhost:${port}/custom-webhook`,
      headers: {
        'content-type': 'application/json' // force the right mime type to send data here
      },
      body: JSON.stringify(sampleData)
    }, (err, response, body) => {
      t.error(err)
      t.strictEqual(response.statusCode, 200)
      t.strictEqual(response.headers['content-type'], 'application/json')
      t.deepEqual(JSON.parse(body), sampleData)
      // TODO: fix last failing test ... wip
      console.log(`Response body: "${body}"`) // TODO: temp ...

      fastify.close()
    })
  })
})

So the question:
how is it the recommended way to let my plugin export some functions but in a way that I could get a reference to them ?
Should I wrap those functions in another source in the plugin exported too ? Or have multiple export items in the plugin (the plugin itself wrapped by fastify-plugin like currently, and handler functions too), like:
module.exports = { fp(fastifyWebHook, { ... }) , loggerWebhookHandler, echoWebhookHandler }
// or maybe wrap both handlers in another function like 'webhookHandlers' and export it
but don't know when I use the plugin (with a require) if all works in a good way.

Having multiple exports from a Fastify Plugin is it good ?

In alternative, move handlers in another node.js package and use here as a dependency seems a little overkill to me (but if it's the right way I can do it) ...

@mcollina What do you think ? Thanks for the help.

Can you please make the code readable?

I think you could add (via fastify.decorate()) :

fastify.webhook({
  url: '..',
  handler: '..'
})

Internally you can call route().

I'lll be happy to review that PR for you.

Can you please make the code readable?
done, sorry for previous formatting ...

In the plugin, the given url is puslished using route:
fastify.post(webhookUrl, webhookHandler)
But I don't understand your suggestion to use decorate ... to add to fastify my handlers ?

Otherwise, if I'd move handlers in another source in the plugin (and exported too) does it interferes with Fastify handling of this plugin when loaded ?

Sorry for all questions, I'm trying to improve my knowledge on Fastify :-) ...

But I don't understand your suggestion to use decorate ... to add to fastify my handlers ?

fastify.decorate('webhook', function (opts) {
  // do some specific thing...
  this.post(.., ..)
})

Then:

fastify.register(fastifyWebHooks)
fastify.register(myPluginThatUsesWebHooks)

Ah ok ... so just to be sure that I fully understand your suggestion:

  • use fastify-webhook to extend fastify via decorate ... great (didn't use up to now)
  • keep the packaging of fastify-webhook as a plugin, but inside it use decorate (and register) to add to it some features that otherwise would be masked by the plugin system, right ?
  • keep the export of the plugin as is (wrapped by fastify-plugin, and as a single object exported)

I'm still trying to better understand other parts of your suggestions ... prepare for other questions during next days :-) . Thanks again. Bye

@mcollina Just pushed an updated version that works ... but up to now I only had to split plugin handlers in another source (exported the same by the plugin) that if/when needed could be loaded via require just before the plugin, for example (extract from plugin tests):

  const fastify = Fastify()
  const webhookHandlers = require('../handlers.js') // get plugin handlers (optional)
  const webhookPlugin = require('../')
  fastify.register(webhookPlugin, {
    'url': '/custom-webhook',
    'handler': webhookHandlers.echo
  })
...

So all seems good even without fastify decorate ... sounds good the same to you ?
Thanks a lot for the help.

It's ok, good work.