fastify-cloudevents
Advanced tools
Comparing version 3.0.0 to 4.0.0
# Change Log | ||
## [4.0.0](https://github.com/smartiniOnGitHub/fastify-cloudevents/releases/tag/4.0.0) (2022-08-16) | ||
[Full Changelog](https://github.com/smartiniOnGitHub/fastify-cloudevents/compare/3.0.0...4.0.0) | ||
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](https://github.com/cloudevents/spec/releases/tag/v1.0.2) | ||
- 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](https://github.com/smartiniOnGitHub/fastify-cloudevents/releases/tag/3.0.0) (2022-04-17) | ||
@@ -4,0 +20,0 @@ [Full Changelog](https://github.com/smartiniOnGitHub/fastify-cloudevents/compare/2.10.0...3.0.0) |
@@ -18,3 +18,3 @@ /* | ||
const assert = require('assert').strict | ||
const assert = require('node:assert').strict | ||
const fastify = require('fastify')() | ||
@@ -49,4 +49,4 @@ const fastifyVersion = require('fastify/package.json').version // get Fastify version | ||
// define a sample id generator here | ||
const hostname = require('os').hostname() | ||
const pid = require('process').pid | ||
const hostname = require('node:os').hostname() | ||
const pid = require('node:process').pid | ||
function * idMakerExample () { | ||
@@ -83,2 +83,3 @@ const idPrefix = `fastify-${fastifyVersion}@${hostname}@${pid}` | ||
onResponseCallback: loggingCallback, | ||
onTimeoutCallback: loggingCallback, | ||
onCloseCallback: loggingCallback, | ||
@@ -113,4 +114,4 @@ onRouteCallback: loggingCallback, | ||
status: 'starting', | ||
hostname: hostname, | ||
pid: pid | ||
hostname, | ||
pid | ||
}, // data | ||
@@ -127,5 +128,5 @@ k.cloudEventOptions, | ||
fastify.get('/', function (req, reply) { | ||
const path = require('path') | ||
const path = require('node:path') | ||
const scriptRelativeFolder = path.join(__dirname, path.sep) | ||
const fs = require('fs') | ||
const fs = require('node:fs') | ||
const stream = fs.createReadStream(path.join(scriptRelativeFolder, 'home.html')) | ||
@@ -155,3 +156,3 @@ reply.type('text/html; charset=utf-8').send(stream) | ||
fastify.listen(k.port, k.address, (err, address) => { | ||
fastify.listen({ port: k.port, host: k.address }, (err, address) => { | ||
const processInfoAsData = fastify.CloudEventTransformer.processInfoToData() | ||
@@ -158,0 +159,0 @@ if (err) { |
@@ -33,4 +33,4 @@ /* | ||
// define a sample id generator here | ||
const hostname = require('os').hostname() | ||
const pid = require('process').pid | ||
const hostname = require('node:os').hostname() | ||
const pid = require('node:process').pid | ||
function * idCounterExample () { | ||
@@ -55,2 +55,3 @@ let counter = 0 | ||
onResponseCallback: loggingCallback, | ||
onTimeoutCallback: loggingCallback, | ||
onCloseCallback: loggingCallback, | ||
@@ -67,5 +68,5 @@ onReadyCallback: loggingCallback, | ||
fastify.get('/', function (req, reply) { | ||
const path = require('path') | ||
const path = require('node:path') | ||
const scriptRelativeFolder = path.join(__dirname, path.sep) | ||
const fs = require('fs') | ||
const fs = require('node:fs') | ||
const stream = fs.createReadStream(path.join(scriptRelativeFolder, 'home.html')) | ||
@@ -95,3 +96,3 @@ reply.type('text/html; charset=utf-8').send(stream) | ||
fastify.listen(k.port, k.address, (err, address) => { | ||
fastify.listen({ port: k.port, host: k.address }, (err, address) => { | ||
if (err) { | ||
@@ -107,4 +108,4 @@ throw err | ||
status: 'listening', | ||
hostname: hostname, | ||
pid: pid | ||
hostname, | ||
pid | ||
}, // data | ||
@@ -128,4 +129,4 @@ k.cloudEventOptions | ||
status: 'ready', | ||
hostname: hostname, | ||
pid: pid | ||
hostname, | ||
pid | ||
}, // data | ||
@@ -132,0 +133,0 @@ k.cloudEventOptions |
{ | ||
"name": "fastify-cloudevents", | ||
"version": "3.0.0", | ||
"version": "4.0.0", | ||
"description": "Fastify Plugin to serialize events in the CloudEvents standard format", | ||
"main": "src/plugin", | ||
"scripts": { | ||
"audit:log": "npm audit > ./temp/audit.log", | ||
"clean:install": "rm -rf ./package-lock.json ./node_modules/", | ||
@@ -20,5 +21,6 @@ "dependency:log": "npm list > ./temp/dependencies.log", | ||
"test:clean": "rm -rf .nyc_output/* ./coverage/*", | ||
"test:coverage:all": "npm run test:unit -- --cov", | ||
"test:coverage": "npm run test:unit -- --cov --coverage-report=html", | ||
"test:unit:debug": "tap -T --node-arg=--inspect-brk test/*.test.js", | ||
"test:unit:dev": "tap -J --watch test/*.test.js", | ||
"test:unit:dev": "tap --watch --cov test/*.test.js", | ||
"test:unit": "tap -J test/*.test.js", | ||
@@ -28,15 +30,15 @@ "test": "npm run lint && npm run test:unit" | ||
"dependencies": { | ||
"cloudevent": "~0.9.0", | ||
"fast-json-stringify": "^2.7.13", | ||
"fastify-plugin": "^3.0.1" | ||
"cloudevent": "~0.10.0", | ||
"fast-json-stringify": "^5.1.0", | ||
"fastify-plugin": "^4.2.0" | ||
}, | ||
"devDependencies": { | ||
"fastify": "^3.3.0", | ||
"jsdoc": "^3.6.10", | ||
"standard": "^16.0.4", | ||
"tap": "^15.2.3" | ||
"fastify": "^4.0.1", | ||
"jsdoc": "^3.6.11", | ||
"standard": "^17.0.0", | ||
"tap": "^16.3.0" | ||
}, | ||
"peerDependencies": {}, | ||
"engines": { | ||
"node": ">=10.13.0" | ||
"node": ">=14.15.0" | ||
}, | ||
@@ -43,0 +45,0 @@ "homepage": "https://github.com/smartiniOnGitHub/fastify-cloudevents#readme", |
@@ -6,4 +6,4 @@ # fastify-cloudevents | ||
[![Code Style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg?style=flat)](http://standardjs.com/) | ||
[![Coverage Status](https://coveralls.io/repos/github/smartiniOnGitHub/fastify-cloudevents/badge.svg?branch=master)](https://coveralls.io/github/smartiniOnGitHub/fastify-cloudevents/?branch=master) | ||
[![Known Vulnerabilities](https://snyk.io//test/github/smartiniOnGitHub/fastify-cloudevents/badge.svg?targetFile=package.json)](https://snyk.io//test/github/smartiniOnGitHub/fastify-cloudevents?targetFile=package.json) | ||
[![license - APACHE-2.0](https://img.shields.io/npm/l/fastify-cloudevents.svg)](http://opensource.org/licenses/APACHE-2.0) | ||
@@ -49,3 +49,6 @@ Fastify Plugin to transform events in/from the CloudEvents standard format. | ||
fastify.listen(3000) | ||
fastify.listen({ port: 3000, host: 'localhost' }, (err, address) => { | ||
if (err) throw err | ||
console.log(`server listening on ${address}`) | ||
}) | ||
``` | ||
@@ -62,5 +65,5 @@ | ||
Fastify ^3.3.0 , Node.js 10 LTS (10.13.0) or later. | ||
Fastify ^4.0.1 , Node.js 14 LTS (14.15.0) or later. | ||
Note that plugin releases 2.x are for Fastify 2.x, 3.x are for Fastify 3.x, etc. | ||
Note that plugin releases 3.x are for Fastify 3.x, 4.x are for Fastify 4.x, etc. | ||
@@ -91,15 +94,7 @@ | ||
Plugin options are: | ||
- `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' | ||
- 'pluginServerUrl', use only the given `serverUrl` | ||
- 'pluginAndRequestUrl', use the given `serverUrl` and add the current request url | ||
- 'pluginAndRequestSimplified', use the given `serverUrl` and add the current request url, | ||
but without arguments (if any) | ||
- 'requestUrl', use only the request url | ||
- anything other, will raise an `Error` | ||
- `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 | ||
@@ -112,23 +107,36 @@ - `includeHeaders`, a boolean flag to add request headers in generated CloudEvents when `true` | ||
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` | ||
- `preHandlerCallback`, callback to handle generated CloudEvents in Fastify hook `preHandler` | ||
- `preSerializationCallback`, callback to handle generated CloudEvents in Fastify hook `preSerialization` | ||
- `onErrorCallback`, callback to handle generated CloudEvents in Fastify hook `onError` | ||
- `onSendCallback`, callback to handle generated CloudEvents in Fastify hook `onSend` | ||
- `onResponseCallback`, callback to handle generated CloudEvents in Fastify hook `onResponse` | ||
- `onCloseCallback`, callback to handle generated CloudEvents in Fastify hook `onClose`, for the plugin | ||
- `onRouteCallback`, callback to handle generated CloudEvents in Fastify hook `onRoute` | ||
- `onRegisterCallback`, callback to handle generated CloudEvents in Fastify hook `onRegister` | ||
- `onReadyCallback`, callback to handle the generated CloudEvent in Fastify lifecycle function `ready`, | ||
for the plugin (when the plugin has been loaded) | ||
- `cloudEventOptions`, CloudEvent options common to all generated event instances; | ||
anyway objects are copied to not be shared between instances | ||
all plugin options have a default value, so are optional. | ||
all plugin options are optional, and have a default value. | ||
See [README - cloudevent.js - GitHub](https://github.com/smartiniOnGitHub/cloudevent.js/blob/master/README.md) 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](https://github.com/fastify/fastify/blob/main/docs/Reference/Hooks.md) for more info on Fastify Hooks. | ||
Note that there is even the ability to validate CloudEvent instances | ||
@@ -135,0 +143,0 @@ in a stricter way, by setting to true the attribute 'strict' in constructor options; |
@@ -23,2 +23,15 @@ /* | ||
* Should not be used outside of the plugin. | ||
* @module utility | ||
*/ | ||
/** | ||
* Get a reference to CloudEvent class definition and related utilities. | ||
* See {@link CloudEvent}. | ||
* @private | ||
*/ | ||
const { CloudEvent, CloudEventTransformer } = require('cloudevent') | ||
/** | ||
* Utility function for creating grouped values to use in Cloudevents. | ||
* Should not be used outside of the plugin. | ||
* | ||
@@ -29,5 +42,2 @@ * @param {!object} options configuration options | ||
*/ | ||
const { CloudEvent, CloudEventTransformer } = require('cloudevent') // get CloudEvent definition and related utilities | ||
function builder (options = {}) { | ||
@@ -184,3 +194,3 @@ const { | ||
timestamp: CloudEventTransformer.timestampToNumber(), | ||
description: description, | ||
description, | ||
name: pluginName, | ||
@@ -187,0 +197,0 @@ version: pluginVersion |
@@ -22,9 +22,10 @@ /* | ||
* useful to use Cloudevents even before registering this plugin. | ||
* @module utility | ||
*/ | ||
/** | ||
* Get a reference to cloudevent class. | ||
* Get a reference to cloudevent class and related utilities. | ||
*/ | ||
const CloudEventLibrary = require('cloudevent') // get CloudEvent definition and related utilities | ||
const CloudEventLibrary = require('cloudevent') | ||
module.exports = CloudEventLibrary |
@@ -18,2 +18,8 @@ /* | ||
/** | ||
* Plugin: | ||
* this module exports the plugin as an async function. | ||
* @module plugin | ||
*/ | ||
const fp = require('fastify-plugin') | ||
@@ -25,7 +31,42 @@ const { CloudEvent, CloudEventTransformer, JSONBatch } = require('cloudevent') // get CloudEvent definition and related utilities | ||
/** | ||
* Plugin implementation. | ||
* Note that's an async function. | ||
* | ||
* @param {!object} fastify Fastify instance | ||
* @param {object} [options={}] plugin configuration options | ||
* <ul> | ||
* <li>baseNamespace (string, default `com.github.fastify.plugins.${pluginName}-v${pluginVersion}`) as base namespace for events generated,</li> | ||
* <li>cloudEventExtensions (object, default null) Extensions for events generated,</li> | ||
* <li>cloudEventOptions (object, default empty) Options for events generated,</li> | ||
* <li>idGenerator (function, default idMaker) to build ID for events generated,</li> | ||
* <li>includeHeaders (boolean, default false) flag to enable the add HTTP request Headers in events generated,</li> | ||
* <li>includeHttpAttributes (boolean, default false) flag to add some HTTP request attributes in events generated,</li> | ||
* <li>includeRedundantAttributes` (boolean, default false) flag to add some redundant attributes inside data in events generated,</li> | ||
* <li>onCloseCallback (function, no default) callback function for the 'onClose' hook,</li> | ||
* <li>onErrorCallback (function, no default) callback function for the 'onError' hook,</li> | ||
* <li>onReadyCallback (function, no default) callback function for the 'onReady' hook,</li> | ||
* <li>onRegisterCallback (function, no default) callback function for the 'onRegister' hook,</li> | ||
* <li>onRequestCallback (function, no default) callback function for the 'onRequest' hook,</li> | ||
* <li>onResponseCallback (function, no default) callback function for the 'onResponse' hook,</li> | ||
* <li>onRouteCallback (function, no default) callback function for the 'onRoute' hook,</li> | ||
* <li>onSendCallback (function, no default) callback function for the 'onSend' hook,</li> | ||
* <li>onTimeoutCallback (function, no default) callback function for the 'onTimeout' hook,</li> | ||
* <li>preHandlerCallback (function, no default) callback function for the 'preHandler' hook,</li> | ||
* <li>preParsingCallback (function, no default) callback function for the 'preParsing' hook,</li> | ||
* <li>preSerializationCallback (function, no default) callback function for the 'preSerialization' hook,</li> | ||
* <li>preValidationCallback (function, no default) callback function for the 'preValidation' hook,</li> | ||
* <li>serverUrl (string, default '/') used as base to calculate source URL in events generated,</li> | ||
* <li>serverUrlMode (string, default null so 'pluginAndRequestSimplified'; other values: 'pluginAndRequestUrl', 'pluginServerUrl','requestUrl') specify the way to calculate source URL in events generated,</li> | ||
* <li>See [README - cloudevent.js - GitHub]{@link https://github.com/smartiniOnGitHub/cloudevent.js/blob/master/README.md} for more info.</li> | ||
* <li>For Hooks, see [Hooks - Fastify reference - GitHub]{@link https://github.com/fastify/fastify/blob/main/docs/Reference/Hooks.md} for more info.</li> | ||
* </ul> | ||
* | ||
* @namespace | ||
*/ | ||
async function fastifyCloudEvents (fastify, options) { | ||
const { | ||
serverUrl = '/', | ||
serverUrlMode = null, | ||
baseNamespace = `com.github.fastify.plugins.${pluginName}-v${pluginVersion}`, | ||
cloudEventExtensions = null, | ||
cloudEventOptions = {}, | ||
idGenerator = idMaker(), | ||
@@ -35,18 +76,22 @@ includeHeaders = false, | ||
includeRedundantAttributes = false, | ||
onCloseCallback = null, | ||
onErrorCallback = null, | ||
onReadyCallback = null, | ||
onRegisterCallback = null, | ||
onRequestCallback = null, | ||
onResponseCallback = null, | ||
onRouteCallback = null, | ||
onSendCallback = null, | ||
onTimeoutCallback = null, | ||
preHandlerCallback = null, | ||
preParsingCallback = null, | ||
preSerializationCallback = null, | ||
preValidationCallback = null, | ||
preHandlerCallback = null, | ||
preSerializationCallback = null, | ||
onErrorCallback = null, | ||
onSendCallback = null, | ||
onResponseCallback = null, | ||
onCloseCallback = null, | ||
onRouteCallback = null, | ||
onRegisterCallback = null, | ||
onReadyCallback = null, | ||
cloudEventOptions = {}, | ||
cloudEventExtensions = null | ||
serverUrl = '/', | ||
serverUrlMode = null | ||
} = options | ||
ensureIsObjectPlain(fastify, 'fastify') | ||
// ensureIsObjectPlain(options, 'options') | ||
ensureIsString(serverUrl, 'serverUrl') | ||
@@ -71,2 +116,3 @@ ensureIsString(serverUrlMode, 'serverUrlMode') | ||
ensureIsFunction(onReadyCallback, 'onReadyCallback') | ||
ensureIsFunction(onTimeoutCallback, 'onTimeoutCallback') | ||
ensureIsObjectPlain(cloudEventOptions, 'cloudEventOptions') | ||
@@ -94,15 +140,34 @@ ensureIsObjectPlain(cloudEventExtensions, 'cloudEventExtensions') | ||
* @param {object} [options={}] optional serialization attributes: | ||
* encoder (function, no default) a function that takes data and returns encoded data, | ||
* encodedData (string, no default) already encoded data (but consistency with the datacontenttype is not checked), | ||
* onlyValid (boolean, default false) to serialize only if it's a valid instance, | ||
* <ul> | ||
* <li>encoder (function, no default) a function that takes data and returns encoded data as a string,</li> | ||
* <li>encodedData (string, no default) already encoded data (but consistency with the datacontenttype is not checked),</li> | ||
* <li>onlyValid (boolean, default false) to serialize only if it's a valid instance,</li> | ||
* <li>printDebugInfo (boolean, default false) to print some debug info to the console,</li> | ||
* <li>timezoneOffset (number, default 0) to apply a different timezone offset,</li> | ||
* <li>See [CloudEvent]{@link https://github.com/smartiniOnGitHub/cloudevent.js/blob/master/src/cloudevent.js} and its [static method serializeEvent]{@link CloudEvent#serializeEvent} for similar options.</li> | ||
* </ul> | ||
* @return {string} the serialized event, as a string | ||
* @throws {Error} if event is undefined or null, or an option is undefined/null/wrong | ||
* @throws {Error} if onlyValid is true, and the given event is not a valid CloudEvent instance | ||
* | ||
* @inner | ||
*/ | ||
function serialize (event, { encoder, encodedData, onlyValid = false } = {}) { | ||
function serialize (event, { | ||
encoder, encodedData, | ||
onlyValid = false, | ||
printDebugInfo = false, | ||
timezoneOffset = 0 | ||
} = {}) { | ||
ensureIsObjectPlain(event, 'event') | ||
if (printDebugInfo === true) { | ||
console.log(`DEBUG | trying to serialize ce: ${JSON.stringify(event)}`) | ||
} | ||
if (event.datacontenttype === CloudEvent.datacontenttypeDefault()) { | ||
if ((onlyValid === false) || (onlyValid === true && CloudEvent.isValidEvent(event) === true)) { | ||
return stringify(event) | ||
if ((onlyValid === false) || (onlyValid === true && CloudEvent.isValidEvent(event, { timezoneOffset }) === true)) { | ||
const ser = stringify(event) | ||
if (printDebugInfo === true) { | ||
console.log(`DEBUG | ce successfully serialized as: ${ser}`) | ||
} | ||
return ser | ||
} else { | ||
@@ -133,4 +198,8 @@ throw new Error('Unable to serialize a not valid CloudEvent.') | ||
// console.log(`DEBUG - new event details: ${CloudEventTransformer.dumpObject(newEvent, 'newEvent')}`) | ||
if ((onlyValid === false) || (onlyValid === true && CloudEvent.isValidEvent(newEvent) === true)) { | ||
return stringify(newEvent) | ||
if ((onlyValid === false) || (onlyValid === true && CloudEvent.isValidEvent(newEvent, { timezoneOffset }) === true)) { | ||
const ser = stringify(newEvent) | ||
if (printDebugInfo === true) { | ||
console.log(`DEBUG | ce successfully serialized as: ${ser}`) | ||
} | ||
return ser | ||
} else { | ||
@@ -143,4 +212,12 @@ throw new Error('Unable to serialize a not valid CloudEvent.') | ||
const Ajv = require('ajv') | ||
const ajv = new Ajv({ coerceTypes: true, removeAdditional: true }) | ||
const validateFromSchema = ajv.compile(ceSchema) | ||
const addFormats = require('ajv-formats') | ||
// define some default options for Ajv | ||
const defaultAjvValidationOptions = { | ||
coerceTypes: true, | ||
removeAdditional: true | ||
} | ||
// create a default instance for Ajv and related schema validator | ||
const defaultAjv = new Ajv(defaultAjvValidationOptions) | ||
addFormats(defaultAjv) | ||
const defaultAjvValidateFromSchema = defaultAjv.compile(ceSchema) | ||
@@ -150,9 +227,22 @@ /** | ||
* | ||
* @param {!object} event the CloudEvent to serialize | ||
* @return {object} validation results: 'valid' boolean and 'errors' as array of strings or null | ||
* @param {!object} event the CloudEvent to validate | ||
* @param {object} [options=null] Ajv validation options, see {@link https://ajv.js.org/options.html|Options - AJV Validator} | ||
* @return {object} object with validation results: 'valid' boolean and 'errors' as array of strings or null | ||
* @throws {Error} if event is undefined or null | ||
* | ||
* @inner | ||
*/ | ||
function validate (event) { | ||
function validate (event, options = null) { | ||
ensureIsObjectPlain(event, 'event') | ||
// depending on options given, it will be used a new Ajv instance | ||
// or one already created with default settings, to speedup validation | ||
let ajv = defaultAjv | ||
let validateFromSchema = defaultAjvValidateFromSchema | ||
if (options !== null) { | ||
ajv = new Ajv(options) | ||
addFormats(ajv) | ||
validateFromSchema = ajv.compile(ceSchema) | ||
} | ||
const isValid = validateFromSchema(event) | ||
@@ -193,2 +283,4 @@ return { | ||
// handle hooks, only when related callback are defined | ||
// see [Hooks - Fastify reference - GitHub](https://github.com/fastify/fastify/blob/main/docs/Reference/Hooks.md) | ||
if (onRequestCallback !== null) { | ||
@@ -206,3 +298,3 @@ fastify.addHook('onRequest', async (request, reply) => { | ||
// send the event to the callback | ||
onRequestCallback(ce) | ||
await onRequestCallback(ce) | ||
}) | ||
@@ -215,3 +307,3 @@ } | ||
null) // do not pass payload here or a "Converting circular structure to JSON" will be raised if enabled ... | ||
preParsingCallback(ce) | ||
await preParsingCallback(ce) | ||
}) | ||
@@ -223,3 +315,3 @@ } | ||
const ce = builders.buildCloudEventForHook('preValidation', request, reply) | ||
preValidationCallback(ce) | ||
await preValidationCallback(ce) | ||
}) | ||
@@ -231,3 +323,3 @@ } | ||
const ce = builders.buildCloudEventForHook('preHandler', request, reply) | ||
preHandlerCallback(ce) | ||
await preHandlerCallback(ce) | ||
}) | ||
@@ -239,3 +331,3 @@ } | ||
const ce = builders.buildCloudEventForHook('preSerialization', request, reply, payload) | ||
preSerializationCallback(ce) | ||
await preSerializationCallback(ce) | ||
}) | ||
@@ -269,3 +361,3 @@ } | ||
) | ||
onErrorCallback(ce) | ||
await onErrorCallback(ce) | ||
// done() // do not pass the error to the done callback here | ||
@@ -278,3 +370,3 @@ }) | ||
const ce = builders.buildCloudEventForHook('onSend', request, reply, payload) | ||
onSendCallback(ce) | ||
await onSendCallback(ce) | ||
}) | ||
@@ -287,6 +379,14 @@ } | ||
// keep the request attribute from data, even if more data will be shown here | ||
onResponseCallback(ce) | ||
await onResponseCallback(ce) | ||
}) | ||
} | ||
if (onTimeoutCallback !== null) { | ||
fastify.addHook('onTimeout', async (request, reply) => { | ||
const ce = builders.buildCloudEventForHook('onTimeout', request, reply) | ||
// keep the request attribute from data, even if more data will be shown here | ||
await onTimeoutCallback(ce) | ||
}) | ||
} | ||
if (onCloseCallback !== null) { | ||
@@ -302,3 +402,3 @@ // hook to plugin shutdown | ||
) | ||
onCloseCallback(ce) | ||
await onCloseCallback(ce) | ||
}) | ||
@@ -308,3 +408,3 @@ } | ||
if (onRouteCallback !== null) { | ||
fastify.addHook('onRoute', async (routeOptions) => { | ||
fastify.addHook('onRoute', (routeOptions) => { | ||
const ce = new fastify.CloudEvent(idGenerator.next().value, | ||
@@ -322,3 +422,3 @@ `${baseNamespace}.onRoute`, | ||
if (onRegisterCallback !== null) { | ||
fastify.addHook('onRegister', async (instance, opts) => { | ||
fastify.addHook('onRegister', (instance, opts) => { | ||
const ce = new fastify.CloudEvent(idGenerator.next().value, | ||
@@ -345,3 +445,3 @@ `${baseNamespace}.onRegister`, | ||
) | ||
onReadyCallback(ce) | ||
await onReadyCallback(ce) | ||
}) | ||
@@ -353,2 +453,4 @@ } | ||
// utility functions | ||
function ensureIsString (arg, name = 'arg') { | ||
@@ -384,3 +486,3 @@ if (arg !== null && typeof arg !== 'string') { | ||
const hostname = require('os').hostname() | ||
const hostname = require('node:os').hostname() | ||
const idPrefix = `fastify@${hostname}` | ||
@@ -405,4 +507,4 @@ function * idMaker () { | ||
module.exports = fp(fastifyCloudEvents, { | ||
fastify: '^3.3.0', | ||
fastify: '^4.0.1', | ||
name: 'fastify-cloudevents' | ||
}) |
Sorry, the diff of this file is not supported yet
Filesystem access
Supply chain riskAccesses the file system, and could potentially read sensitive data.
Found 1 instance in 1 package
78659
1029
177
0
+ Added@fastify/merge-json-schemas@0.1.1(transitive)
+ Addedajv@8.17.1(transitive)
+ Addedajv-formats@3.0.1(transitive)
+ Addedcloudevent@0.10.0(transitive)
+ Addedfast-json-stringify@5.16.1(transitive)
+ Addedfast-uri@2.4.03.0.5(transitive)
+ Addedfastify-plugin@4.5.1(transitive)
+ Addedjson-schema-ref-resolver@1.0.1(transitive)
+ Addedjson-schema-traverse@1.0.0(transitive)
+ Addedrequire-from-string@2.0.2(transitive)
- Removedajv@6.12.6(transitive)
- Removedcloudevent@0.9.0(transitive)
- Removeddeepmerge@4.3.1(transitive)
- Removedfast-json-stable-stringify@2.1.0(transitive)
- Removedfast-json-stringify@2.7.13(transitive)
- Removedfastify-plugin@3.0.1(transitive)
- Removedjson-schema-traverse@0.4.1(transitive)
- Removedpunycode@2.3.1(transitive)
- Removedstring-similarity@4.0.4(transitive)
- Removeduri-js@4.4.1(transitive)
Updatedcloudevent@~0.10.0
Updatedfast-json-stringify@^5.1.0
Updatedfastify-plugin@^4.2.0