Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

fastify-cloudevents

smartiniOnGitHub268Apache-2.04.0.0

Fastify Plugin to serialize events in the CloudEvents standard format

fastify, plugin, cloudevents

readme

fastify-cloudevents

NPM Version NPM Downloads Code Style Known Vulnerabilities license - APACHE-2.0

Fastify Plugin to transform events in/from the CloudEvents standard format.

Current release uses the v1.0.2 of the CloudEvents Spec.

The purpose of this plugin is to let Fastify web applications create instances of CloudEvents in a simple way (with some useful defaults), or in a full way (all attributes). Optionally, it's possible to validate created instances to be sure they are compliant with the standard. Then, created instances can be serialized, for example to be sent (or saved/stored) somewhere. It's possible even to deserialize (parse) a string into a CloudEvent instance.

Other features of the plugin: enable forwarding of Fastify events to given callbacks (using hooks), and wrapping main data of the original event in a specific CloudEvent instance.

Note that all CloudEvents features exposed here are in the the library cloudevent.

Usage

const fastify = require('fastify')()

// define functions to use in plugin configuration:
// idExample generator, callbackExample(ce) , etc ...

// register the plugin with some options, for example:
fastify.register(require('fastify-cloudevents'), {
  serverUrl: 'http://0.0.0.0:3000',
  idGenerator: idExample,
  onRequestCallback: callbackExample,
  onErrorCallback: callbackExample,
  onResponseCallback: callbackExample,
  cloudEventOptions: { }
})

// implementation ...

fastify.listen({ port: 3000, host: 'localhost' }, (err, address) => {
  if (err) throw err
  console.log(`server listening on ${address}`)
})

In the example folder there are some simple server scripts that uses the plugin (inline but it's the same using it from npm registry):

  • example is a simple one
  • example-enhanced is a more complex sample to show even how to raise own events (normal, errors, and some custom)

Requirements

Fastify ^4.0.1 , Node.js 14 LTS (14.15.0) or later.

Note that plugin releases 3.x are for Fastify 3.x, 4.x are for Fastify 4.x, etc.

Sources

Source code is all inside main repo: fastify-cloudevents.

Documentation generated from source code (library API): here.

Note

The plugin decorate Fastify and expose some functions:

  • CloudEvent, the CloudEvent implementation, as a class
  • CloudEventTransformer, the CloudEventTransformer utility class
  • JSONBatch, the class to handle JSONBatch instances
  • cloudEventJSONSchema, the JSONSchema for a CloudEvent used in the plugin, as an object
  • cloudEventSerializeFast, a serialize function implemented here using fast-json-stringify and not standard JSON serialization functions; note that similar features of the underlying library has been implemented here (like serialization options)
  • cloudEventValidateFast, a validation function implemented here using ajv (which is a dependency of fast-json-stringify) that uses a schema compiler

Plugin options are:

  • baseNamespace, a base namespace for the type; more specific suffix should be added to it in any CloudEvent
  • cloudEventExtensions, CloudEvent extensions to add in all generated events
  • cloudEventOptions, CloudEvent options common to all generated events; anyway objects are copied to not be shared between instances
  • idGenerator, a generator function that returns the id (if possible, unique) for any CloudEvent
  • includeHeaders, a boolean flag to add request headers in generated CloudEvents when true (by default is false)
  • includeHttpAttributes, a boolean flag to add some HTTP attributes in generated CloudEvents when true (by default is false)
  • includeRedundantAttributes, a boolean flag to add some redundant attributes in the data section of generated CloudEvents when true (by default is false)
  • serverUrl, the URL (absolute, or relative) of the current webapp, to use as a base source in generated CloudEvents
  • serverUrlMode, the mode to build the source attribute in generated CloudEvents; any not null value will cause this setting to be added to extensions (if set not null in plugin options):
    • null, (default value) same as 'pluginAndRequestSimplified' but without arguments (if any)
    • 'pluginAndRequestSimplified', use the given serverUrl and add the current request url,
    • 'pluginAndRequestUrl', use the given serverUrl and add the current request url
    • 'pluginServerUrl', use only the given serverUrl
    • 'requestUrl', use only the request url
    • anything other, will raise an Error
  • onCloseCallback, callback to handle generated CloudEvents in Fastify hook onClose, for the plugin
  • onErrorCallback, callback to handle generated CloudEvents in Fastify hook onError
  • onReadyCallback, callback to handle the generated CloudEvent in Fastify lifecycle function ready, for the plugin (when the plugin has been loaded)
  • onRegisterCallback, callback to handle generated CloudEvents in Fastify hook onRegister
  • onRequestCallback, callback to handle generated CloudEvents in Fastify hook onRequest
  • onResponseCallback, callback to handle generated CloudEvents in Fastify hook onResponse
  • onRouteCallback, callback to handle generated CloudEvents in Fastify hook onRoute
  • onSendCallback, callback to handle generated CloudEvents in Fastify hook onSend
  • onTimeoutCallback, callback to handle generated CloudEvents in Fastify hook onTimeout
  • preHandlerCallback, callback to handle generated CloudEvents in Fastify hook preHandler
  • preParsingCallback, callback to handle generated CloudEvents in Fastify hook preParsing
  • preSerializationCallback, callback to handle generated CloudEvents in Fastify hook preSerialization
  • preValidationCallback, callback to handle generated CloudEvents in Fastify hook preValidation all plugin options have a default value, so are optional.

See README - cloudevent.js - GitHub for more info on events. Note that all callbacks given to hooks accepts only a single argument: the generated CloudEvent instance, and not arguments like in error-first callbacks: (error, data), because here is not really needed. Most callbacks now here are async. See Hooks - Fastify reference - GitHub for more info on Fastify Hooks.

Note that there is even the ability to validate CloudEvent instances in a stricter way, by setting to true the attribute 'strict' in constructor options; that attribute (when set) will be put in the extensions of the instance. Otherwise you can specify it only during validation, in validation options.

You can find Code Documentation for the API of the library here.

Since v0.2 of the spec, there is no more a standard attribute to specify the version of any specific event type, so the best if to follow their recommendations, and for example add a version in the 'type' attribute (for example '-v1.0.0' at the end of its base value, or at the end of its full value), or into the 'schemaurl' attribute but only its major version (like '-v1' or '/v1/' at the end). Since v0.3 of the spec, extensions are no more inside a specific attribute; as recommended even mine (for the 'strict' mode for example) has been moved into a namespaced one; plugin extensions ('serverUrlMode') has been moved in another (specific) namespace. Since v1.0 of the spec, some properties has been removed/simplified; extension properties must be simple (no nested properties) and must contain only lowercase letters and numbers in the name (and less than 20 chars in total); so for example my strict extension now is 'strictvalidation' with a boolean value. Even my plugin extension now is 'fastifyserverurlmode' with a string value.

For more info on the standard, see the CloudEvents Specification.

Contributing

  1. Fork it ( https://github.com/smartiniOnGitHub/fastify-cloudevents/fork )
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Add some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create a new Pull Request

License

Licensed under Apache-2.0.


changelog

Change Log

4.0.0 (2022-08-16)

Full Changelog Summary Changelog:

  • Updated requirements to Fastify '^4.0.1' and Fastify-plugin '^4.2.0', so require Node.js 14 LTS
  • Updated all dependencies to latest (for Node.js 14 LTS)
  • Use 'cloudevent' latest release ('~0.10.0') which implements the v1.0.2 - CloudEvents Spec
  • Ensure all works again
  • Update serialize function with some useful options (like in the 'cloudevent' library)
  • Update validate function with the ability to pass custom AJV options if/when needed
  • Update and add some hooks for Fastify 4.x; keep them async
  • Remove/update some code now deprecated
  • Refactor CloudEvents creation in tests, for better consistency
  • Ensure all works with latest Node.js 14 LTS and later LTS releases
  • Improve JSDoc comments, generated documentation is much better now

3.0.0 (2022-04-17)

Full Changelog Summary Changelog:

  • Update requirements to latest Fastify 3.x and Node.js 10 LTS
  • Use 'cloudevent' latest release ('~0.9.0') which implements the v1.0.2 - CloudEvents Spec
  • Ensure all works again
  • Update the plugin to be async (thanks to Fastify 3.x features)
  • Update some hooks for Fastify 3.x; keep them async
  • Remove/update some code now deprecated
  • Ensure all works with latest Node.js 10 (even if in End-of-Life status), 12 (even if in End-of-Life status soon), 14 LTS, 16 LTS
  • Note: this plugin release has same features of previous release

2.10.0 (2022-04-16)

Full Changelog Summary Changelog:

  • Update dependency on cloudevent to '0.9.x' which implements the v1.0.2 - CloudEvents Spec with some simplifications/clarifications
  • Update requirements to latest Fastify 2.x, so currently release '^2.15.3'
  • Update all other dependencies
  • Breaking change: update requirements to Node.js 10 LTS
  • Breaking change: the 'time' attribute now is managed as a string in the ISO format (accordingly with the spec format and schema) but constructor will accept same inputs (undefined/null, a Date, now even a string that could be checked during validation of the event); a getter method 'timeAsDate' has been added just for convenience
  • Note: this is last release for Fastify 2.x

2.6.0 (2021-03-28)

Full Changelog Summary Changelog:

  • Update dependency on cloudevent to '0.8.x' which implements the v1.0.1 - CloudEvents Spec with many simplifications/clarifications on v1.0
  • Update requirements to latest Fastify 2.x, so currently release '^2.15.3'
  • Feature: keep compatibility with Node.js 8 (only for plugin releases 2.x)
  • Feature: add to Fastify a decorator to return the JSONSchema (for a CloudEvent) used in the plugin (with some small tweaks), instead of retrieving it from the underlying library
  • Feature: update fast serialization to handle even data as value (string or boolean or number) with datacontenttype not default (for example 'text/plain')
  • Feature: add to Fastify a decorator to add a function that validates with a schema compiler and return validation results and errors (if any)
  • Feature: generate documentation from sources with JSDoc

2.5.0 (2020-10-02)

Full Changelog Summary Changelog:

  • Update requirements to latest Fastify 2.x, so currently release '^2.15.0'
  • Feature: update the 'onReady' hook due to an improvement done in Fastify 2.15.0
  • Feature: keep compatibility with Node.js 8 (only for plugin releases 2.x)

2.4.0 (2020-10-01)

Full Changelog Summary Changelog:

  • Update dependency on cloudevent to '0.7.x' which implements the v1.0 - CloudEvents Spec with all breaking changes since its v0.3
  • Update requirements to a more recent Fastify, release '^2.12.0'
  • Feature: keep compatibility with Node.js 8
  • Update dependencies for the development environment
  • Other minor changes

2.3.0 (2019-11-08)

Full Changelog Summary Changelog:

  • Update dependency on cloudevent to '0.6.x' which implements the v0.3 - CloudEvents Spec with all breaking changes since its v0.2
  • Breaking Change: CloudEvent constructor signature has changed a little, to handle extensions as per spec
  • Breaking Change: CloudEvent attributes has been renamed for better consistency with the spec, and renamed related methods too
  • Updated all dependencies
  • Update requirements to a more recent Fastify, release '^2.7.1'
  • Updated documentation and samples to describe/show changes and the new behavior
  • Export even JSONBatch via Fastify decorators
  • Add plugin option flags to enable the output of redundant attributes and HTTP attributes
  • Fix usage of request url (fix already present in 2.2.1)
  • Clarify and cleanup docs and examples
  • Add npm custom commands to run examples and tests in debug mode
  • Other minor changes

2.2.1 (2019-10-23)

Summary Changelog:

  • Updated all dependencies
  • Fix usage of request url

2.2.0 (2019-05-02)

Full Changelog Summary Changelog:

  • Update dependency on cloudevent to '0.5.x' which implements the v0.2 - CloudEvents Spec with all breaking changes since its v0.1
  • Updated dependencies for the development environment
  • Updated documentation and samples to describe/show changes and the new behavior
  • Updated Tap unit tests to always run in strict mode, and some refactoring
  • Clarify which CloudEvents Spec version is implemented in the current release

2.0.0 (2019-04-08)

Full Changelog Summary Changelog:

  • Update requirements to Fastify v2
  • Update all dependencies
  • Breaking Change: add new Hooks (available since Fastify v2) and remove old ones; hook functions arguments has changed in v2, even for already existing hooks.
  • Improve data set into CloudEvent instances; make data more consistent using the same builder functions
  • Update documentation and examples

1.0.0 (2019-03-26)

Summary Changelog:

  • Updated all dependencies
  • Note that this release number means that the plugin is stable, and for Fastify v1
  • Test example server scripts under load, using clinic and autocannon, to ensure that there aren't memory leaks, slowness, or other problems
  • Small updates in code and examples
  • Pin dependency on cloudevent to '0.4.x'

0.4.0 (2019-03-16)

Summary Changelog:

  • Update docs and examples to show the usage of new plugin features
  • Update all dependencies to latest release, but stay on Fastify v1 for now
  • In plugin option serverUrlMode add a new value (default choice now) 'pluginAndRequestSimplified' to simplify (remove URL arguments) when building the value for the 'sourceURL' attribute
  • In serialize function, add a boolean option 'onlyValid' (by default false) to serialize only a valid CloudEvent instance
  • Remove some inline logic and instead use methods exposed by Transformer (from the CloudEvent library)
  • Other small improvements to go towards plugin '1.0.0'
  • Update tests due to some behavior (for edge cases) was fixed in the CloudEvent library
  • Improve (a little) test code coverage for functions exposed by the plugin

0.3.0 (2019-03-04)

Summary Changelog:

  • Update cloudevent to '0.3.0', with some breaking changes (as usual for dependency use "cloudevent": "^0.3.0")
  • Update docs and examples to show the usage of plugin features
  • Update all dependencies to latest release
  • Update tests

0.2.4 (2019-02-18)

Summary Changelog:

  • Change dependencies to stay on cloudevent to '0.2.x', because the '0.3.0' has some breaking changes (so use "cloudevent": "~0.2.2")
  • Update all dependencies to latest release
  • Update tests

0.2.3 (2019-01-22)

Summary Changelog:

  • Update cloudevent to '0.2.2', with the ability to get CloudEvent data (payload), and the ability to serialize even with a non default contentType
  • Update plugin exposed function for fast serialization ('cloudEventSerializeFast') to accept serialization options (like in 'cloudevent') to be able to serialize even with a non default contentType
  • Updated dependencies to latest release
  • Updated README with serialization options, and a reference to the new package name of the underlying library
  • Add npm custom command to run Tap unit tests with nodejs debugger breaks enabled (inspector)
  • Other small fixes

0.2.2 (2018-12-25)

Summary Changelog:

  • Updated dependencies to latest release
  • Add client IP address in a custom attribute inside the data section of generated CloudEvent instances

0.2.1 (2018-12-20)

Summary Changelog:

  • Update cloudevent to '0.2.1', to remove JSON schema from here and use that exposed by that library
  • Updated dependencies to latest release
  • Other small fixes

0.2.0 (2018-12-17)

Summary Changelog:

  • Update cloudevent.js to '0.2.0', with some breaking changes inside (like the source parameter moved outside its options, etc)
  • Change dependency from cloudevent.js to the new name cloudevent more searchable (the old name is deprecated)
  • Update Fastify dependencies to '1.1.0' or higher (but on 1.x)
  • Add plugin option serverUrlMode (by default null) to specify in which mode source must be constructed in generated CloudEvent instances; see in the README for related values to use. As a sample, add in the example-enhanced with a value to have the same behavior of its default, but that way it will be put in CloudEvent extension object.

0.1.4 (2018-11-15)

Summary Changelog:

  • Tweak implementation for the plugin configuration option includeHeaders and update examples

0.1.3 (2018-11-14)

Summary Changelog:

  • Add the plugin configuration option includeHeaders so that when true all request headers will be put in generated CloudEvents (but by default is false)
  • Update both examples with both values for the plugin configuration option includeHeaders to se default behavior (written the same) and not

0.1.2 (2018-11-13)

Summary Changelog:

  • Maintenance release to fix Fastify dependencies to '1.x' to avoid breaking changes because Fastify '2.x' will be released soon
  • Updated dependencies to latest Fastify plugin (1.2.1) and Fastify 1.x (1.13.0)

0.1.1 (2018-11-06)

Summary Changelog:

  • Maintenance release to fix the usage of generator functions (as ID generator), both in the plugin and in all examples

0.1.0 (2018-11-05)

Summary Changelog:

  • First release compliant with current CloudEvent Spec (0.1.0), with basic features implemented; more to follow in next releases
  • Implement a custom serialization (fast), but only with the default contentType for now
  • Provide some Node.js Examples (basic and enhanced)