-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnodejs-base.js
More file actions
394 lines (375 loc) · 20.4 KB
/
Copy pathnodejs-base.js
File metadata and controls
394 lines (375 loc) · 20.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
/*
* Copyright 2018-2026 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict'
/**
* Sample Node.js script to show usage of CloudEvent library
*/
const assert = require('node:assert').strict
// import some common example data
const {
// commonEventTime,
ceCommonData,
ceCommonExtensions,
ceCommonOptions,
ceCommonOptionsForTextData,
ceCommonOptionsStrict,
ceDataAsJSONString,
ceDataAsString,
ceDataAsStringEncoded,
ceNamespace,
ceOptionsNoStrict,
// ceOptionsStrict,
ceServerUrl,
valOnlyValidAllInstance,
valOnlyValidInstance,
valOptionsNoStrict,
valOptionsStrict
} = require('./common-example-data')
console.log('Sample script: start execution ...\n')
// reference the library, not needed if using destructuring assignment, see below
const CloudEventExports = require('../src/') // from local path
assert(CloudEventExports !== null)
// get a reference only to cloudevent class definition/s
// const { CloudEvent } = require('cloudevent') // from published module
// const { CloudEvent } = require('../src/') // from local path
const {
CloudEvent,
CloudEventValidator: V,
CloudEventTransformer: T,
JSONBatch
} = require('../src/') // from local path
assert(CloudEvent !== null && V !== null && T !== null && JSONBatch !== null)
// create some sample instances but without mandatory fields (so not good for validation) ...
// note that errors will be thrown at instance creation only when strict mode is true
console.log('\nCreation of some CloudEvent (ce) instances, and related diagnostics:')
const ceEmpty = new CloudEvent() // create an empty CloudEvent instance (not valid for the validator, even in default case, when strict mode flag is disabled)
assert(ceEmpty !== null)
console.log(`ce dump (but not good for validation): ${T.dumpObject(ceEmpty, 'ceEmpty')}`)
const ceMinimalMandatoryUndefinedNoStrict = new CloudEvent(undefined, undefined, undefined, undefined, ceOptionsNoStrict) // expected success
assert(ceMinimalMandatoryUndefinedNoStrict !== null)
console.log(`ce dump (but not good for validation): ${T.dumpObject(ceMinimalMandatoryUndefinedNoStrict, 'ceMinimalMandatoryUndefinedNoStrict')}`)
// const ceMinimalMandatoryUndefinedStrict = new CloudEvent(undefined, undefined, undefined, undefined, ceOptionsStrict) // expected failure
// assert(ceMinimalMandatoryUndefinedStrict == null) // no, ReferenceError: ceMinimalMandatoryUndefinedStrict is not defined
// create a sample minimal instance good for normal validation but not for strict validation ...
const ceMinimalBadSource = new CloudEvent('1', ceNamespace, 'source (bad)', null)
assert(ceMinimalBadSource !== null)
console.log(`ce dump (good but not for strict validation): ${T.dumpObject(ceMinimalBadSource, 'ceMinimalBadSource')}`)
// create a sample minimal instance ...
const ceMinimal = new CloudEvent('1', // id
ceNamespace, // type
'/', // source
{} // data (empty) // optional, but useful the same in this sample usage
)
assert(ceMinimal !== null)
console.log(`ce dump: ${T.dumpObject(ceMinimal, 'ceMinimal')}`)
// When creating some instances with an undefined mandatory argument (handled by defaults),
// but with strict flag disabled success is expected, otherwise with strict flag enabled a failure is expected ...
// In JavaScript, null values are not handled as default values, only undefined values ...
// create a sample instance with most common attributes defined ...
const ceFull = new CloudEvent('1/full',
ceNamespace,
ceServerUrl,
ceCommonData, // data
ceCommonOptions,
ceCommonExtensions
)
assert(ceFull !== null)
assert(!ceFull.isStrict)
console.log(`ce dump: ${T.dumpObject(ceFull, 'ceFull')}`)
const ceFullStrict = new CloudEvent('1/full-strict',
ceNamespace,
ceServerUrl,
ceCommonData, // data
ceCommonOptionsStrict, // use common options, but set strict mode to true
ceCommonExtensions
)
assert(ceFullStrict !== null)
assert(ceFullStrict.isStrict)
assert(!ceFull.isStrict) // ensure common options object has not been changed when reusing some of its values for the second instance
assert(!CloudEvent.isStrictEvent(ceFull)) // the same, but using static method
console.log(`ce dump: ${T.dumpObject(ceFullStrict, 'ceFullStrict')}`)
// create an instance with a JSON string as data
const ceFullStrictJSONTextData = new CloudEvent('2/full-strict-json-string-data',
ceNamespace,
ceServerUrl,
ceDataAsJSONString, // data
ceCommonOptionsStrict, // use strict options
ceCommonExtensions
)
assert(ceFullStrictJSONTextData !== null)
assert(ceFullStrictJSONTextData.isStrict)
console.log(`ce dump: ${T.dumpObject(ceFullStrictJSONTextData, 'ceFullStrictJSONTextData')}`)
console.log(`ce validation results on ceFullStrictJSONTextData = ${CloudEvent.validateEvent(ceFullStrictJSONTextData)}`)
// create an instance that wrap an Error
const error = new Error('sample error')
error.code = 1000 // add a sample error code, as number
const errorToData = T.errorToData(error, {
includeStackTrace: true,
// addStatus: false,
addTimestamp: true
})
const ceErrorStrict = new CloudEvent('3/error-strict',
ceNamespace,
ceServerUrl,
errorToData, // data
ceCommonOptionsStrict, // use common options, but set strict mode to true
ceCommonExtensions
)
assert(ceErrorStrict !== null)
assert(ceErrorStrict.isStrict)
console.log(`ce dump: ${T.dumpObject(ceErrorStrict, 'ceErrorStrict')}`)
// create an instance with a different content type
const ceFullStrictOtherContentType = new CloudEvent('4/full-strict-other-content-type',
ceNamespace,
ceServerUrl,
// ceDataAsString, // data
ceCommonData, // data
{ ...ceCommonOptionsStrict, datacontenttype: 'application/xml' }, // use common strict options
ceCommonExtensions
)
assert(ceFullStrictOtherContentType !== null)
assert(ceFullStrictOtherContentType.isStrict)
assert(!ceFull.ceFullStrictOtherContentType) // ensure common options object has not been changed when reusing some of its values for the second instance
assert(!CloudEvent.isStrictEvent(ceFull)) // the same, but using static method
console.log(`ce dump: ${T.dumpObject(ceFullStrictOtherContentType, 'ceFullStrictOtherContentType')}`)
// create an instance with data as a string, but not strict (to validate it even in strict mode)
const ceFullTextData = new CloudEvent('5/no-strict-text-data',
ceNamespace,
ceServerUrl,
ceDataAsString, // data
// ceCommonOptions, // ok but not in strict validation
ceCommonOptionsForTextData, // ok even in strict validation
ceCommonExtensions
)
assert(ceFullTextData !== null)
assert(!ceFullTextData.isStrict)
assert(ceFullTextData.payload === ceDataAsString) // returned data is transformed
console.log(`ce payload: '${ceFullTextData.payload}', length: ${ceFullTextData.payload.length}`)
console.log(`ce dump: ${T.dumpObject(ceFullTextData, 'ceFullTextData')}`)
console.log(`ce validation results on ceFullTextData (no strict validation) = ${CloudEvent.validateEvent(ceFullTextData)}`)
console.log(`ce validation results on ceFullTextData (with strict validation) = ${CloudEvent.validateEvent(ceFullTextData, valOptionsStrict)}`)
// create an instance with data encoded in base64
const ceFullStrictBinaryData = new CloudEvent('6/full-strict-binary-data',
ceNamespace,
ceServerUrl,
null, // data
{ ...ceCommonOptionsStrict, datainbase64: ceDataAsStringEncoded }, // use common strict options, and set binary data in base64
ceCommonExtensions
)
assert(ceFullStrictBinaryData !== null)
assert(ceFullStrictBinaryData.isStrict)
assert(ceFullStrictBinaryData.payload === ceDataAsString) // returned data is transformed
console.log(`ce payload: '${ceFullStrictBinaryData.payload}', length: ${ceFullStrictBinaryData.payload.length}`)
console.log(`ce dump: ${T.dumpObject(ceFullStrictBinaryData, 'ceFullStrictBinaryData')}`)
// validate/check if valid instances (optional)
// then, to validate objects, use class static methods like 'isValidEvent' and 'ValidateEvent', or instance methods like 'isValid', 'validate', etc ...
assert(!ceEmpty.isValid())
assert(!ceMinimalMandatoryUndefinedNoStrict.isValid())
// console.log(`DEBUG | ${CloudEvent.dumpValidationResults(ceMinimalBadSource, null, 'ceMinimalBadSource')}`)
assert(ceMinimalBadSource.isValid())
// console.log(`DEBUG | ${CloudEvent.dumpValidationResults(ceMinimalBadSource, valOptionsStrict, 'ceMinimalBadSource')}`)
assert(!ceMinimalBadSource.isValid(valOptionsStrict))
assert(ceMinimal.isValid())
assert(ceMinimal.isValid(valOptionsStrict))
assert(ceFull.isValid())
assert(ceFullStrict.isValid())
assert(ceFullStrictJSONTextData.isValid())
assert(ceErrorStrict.isValid())
assert(ceFullStrictOtherContentType.isValid())
assert(ceFullTextData.isValid())
assert(ceFullTextData.isValid(valOptionsStrict))
assert(ceFullStrictBinaryData.isValid())
// the same, but using static method
assert(!CloudEvent.isValidEvent(ceEmpty))
assert(!CloudEvent.isValidEvent(ceMinimalMandatoryUndefinedNoStrict))
assert(CloudEvent.isValidEvent(ceMinimal))
assert(CloudEvent.isValidEvent(ceFull))
assert(CloudEvent.isValidEvent(ceFullStrict))
assert(CloudEvent.isValidEvent(ceFullStrictJSONTextData))
assert(CloudEvent.isValidEvent(ceErrorStrict))
assert(CloudEvent.isValidEvent(ceFullStrictOtherContentType))
assert(CloudEvent.isValidEvent(ceFullTextData))
assert(CloudEvent.isValidEvent(ceFullTextData, valOptionsStrict))
assert(CloudEvent.isValidEvent(ceFullStrictBinaryData))
// console.log(`DEBUG | ${CloudEvent.dumpValidationResults(ceEmpty, null, 'ceEmpty')}`)
assert(CloudEvent.validateEvent(ceEmpty).length === 3)
// console.log(`DEBUG | ${CloudEvent.dumpValidationResults(ceEmpty, valOptionsStrict, 'ceEmpty')}`)
assert(CloudEvent.validateEvent(ceEmpty, valOptionsStrict).length === 4)
assert(CloudEvent.validateEvent(ceMinimalMandatoryUndefinedNoStrict).length > 0)
assert(CloudEvent.validateEvent(ceMinimal).length === 0)
assert(CloudEvent.validateEvent(ceFull).length === 0)
assert(CloudEvent.validateEvent(ceFull, valOptionsNoStrict).length === 0)
assert(CloudEvent.validateEvent(ceFull, valOptionsStrict).length === 0)
assert(CloudEvent.validateEvent(ceFullStrict).length === 0)
assert(CloudEvent.validateEvent(ceFullStrict, valOptionsNoStrict).length === 0)
assert(CloudEvent.validateEvent(ceFullStrict, valOptionsStrict).length === 0)
assert(CloudEvent.validateEvent(ceFullStrictJSONTextData).length === 0)
assert(CloudEvent.validateEvent(ceFullStrictJSONTextData, valOptionsNoStrict).length === 0)
assert(CloudEvent.validateEvent(ceFullStrictJSONTextData, valOptionsStrict).length === 0)
assert(CloudEvent.validateEvent(ceFullStrictOtherContentType).length === 0)
assert(CloudEvent.validateEvent(ceFullStrictOtherContentType, valOptionsNoStrict).length === 0)
assert(CloudEvent.validateEvent(ceFullStrictOtherContentType, valOptionsStrict).length === 0)
assert(CloudEvent.validateEvent(ceFullTextData).length === 0)
assert(CloudEvent.validateEvent(ceFullTextData, valOptionsNoStrict).length === 0)
assert(CloudEvent.validateEvent(ceFullTextData, valOptionsStrict).length === 0)
assert(CloudEvent.validateEvent(ceFullStrictBinaryData).length === 0)
assert(CloudEvent.validateEvent(ceFullStrictBinaryData, valOptionsNoStrict).length === 0)
assert(CloudEvent.validateEvent(ceFullStrictBinaryData, valOptionsStrict).length === 0)
// some diagnostic info
console.log('\nSome expected validation errors:')
console.log(`Validation output for ceEmpty (default strict mode) is: size: ${CloudEvent.validateEvent(ceEmpty).length}, details:\n` + CloudEvent.validateEvent(ceEmpty))
console.log(`Validation output for ceEmpty (force strict mode to true) is: size: ${CloudEvent.validateEvent(ceEmpty, valOptionsStrict).length}, details:\n` + CloudEvent.validateEvent(ceEmpty, valOptionsStrict))
console.log(`Validation output for ceEmpty, alternative way: ${CloudEvent.dumpValidationResults(ceEmpty, valOptionsStrict, 'ceEmpty')}`)
// serialization examples
// default contenttype
console.log('\nSome serialization examples:')
const ceFullSerializedStatic = CloudEvent.serializeEvent(ceFull)
assert(ceFullSerializedStatic !== null)
const ceFullSerialized = ceFull.serialize()
assert(ceFullSerialized !== null)
assert(ceFullSerializedStatic === ceFullSerialized)
console.log('Serialization output for ceFull, details:\n' + ceFullSerialized)
const ceFullStrictSerialized = ceFullStrict.serialize()
assert(ceFullStrictSerialized !== null)
console.log('Serialization output for ceFullStrict, details:\n' + ceFullStrictSerialized)
const ceFullStrictSerializedOnlyValid = CloudEvent.serializeEvent(ceFullStrict, valOnlyValidInstance)
assert(ceFullStrictSerializedOnlyValid !== null)
// non default contenttype
const ceFullStrictOtherContentTypeSerializedStatic = CloudEvent.serializeEvent(ceFullStrictOtherContentType, {
// encoder: (data) => '<data "encoder"="sample" />',
encodedData: '<data "hello"="world" "year"="2020" />',
...valOnlyValidInstance
})
assert(ceFullStrictOtherContentTypeSerializedStatic !== null)
const ceFullStrictOtherContentTypeSerialized = ceFullStrictOtherContentType.serialize({
// encoder: (data) => '<data "encoder"="sample" />',
encodedData: '<data "hello"="world" "year"="2020" />',
...valOnlyValidInstance
})
assert(ceFullStrictOtherContentTypeSerialized !== null)
assert(ceFullStrictOtherContentTypeSerializedStatic === ceFullStrictOtherContentTypeSerialized)
console.log('Serialization output for ceFullStrictOtherContentType, details:\n' + ceFullStrictOtherContentTypeSerialized)
const ceFullTextDataSerialized = CloudEvent.serializeEvent(ceFullTextData, valOnlyValidInstance)
assert(ceFullTextDataSerialized !== null)
console.log('Serialization output for ceFullTextData, details:\n' + ceFullTextDataSerialized)
const ceFullStrictBinaryDataSerialized = CloudEvent.serializeEvent(ceFullStrictBinaryData, valOnlyValidInstance)
assert(ceFullStrictBinaryDataSerialized !== null)
console.log('Serialization output for ceFullStrictBinaryData, details:\n' + ceFullStrictBinaryDataSerialized)
// then use (send/store/etc) serialized instances ...
// deserialization examples
// default contenttype
console.log('\nSome deserialization/parse examples:')
const ceFullDeserialized = CloudEvent.deserializeEvent(ceFullSerialized)
assert(ceFullDeserialized !== null)
assert(ceFullDeserialized.isValid())
assert(!ceFullDeserialized.isStrict)
assert(CloudEvent.isCloudEvent(ceFullDeserialized))
console.log(`ce dump: ${T.dumpObject(ceFullDeserialized, 'ceFullDeserialized')}`)
const ceFullStrictDeserializedOnlyValid = CloudEvent.deserializeEvent(ceFullStrictSerialized, valOnlyValidInstance)
assert(ceFullStrictDeserializedOnlyValid !== null)
console.log(`ce dump: ${T.dumpObject(ceFullStrictDeserializedOnlyValid, 'ceFullStrictDeserializedOnlyValid')}`)
// non default contenttype
const ceFullStrictOtherContentTypeDeserialized = CloudEvent.deserializeEvent(ceFullStrictOtherContentTypeSerialized, {
// decoder: (data) => { decoder: 'Sample' },
decodedData: { hello: 'world', year: 2020 },
...valOnlyValidInstance
})
assert(ceFullStrictOtherContentTypeDeserialized !== null)
assert(ceFullStrictOtherContentTypeDeserialized.isValid())
assert(ceFullStrictOtherContentTypeDeserialized.isStrict)
assert(CloudEvent.isCloudEvent(ceFullStrictOtherContentTypeDeserialized))
console.log(`ce dump: ${T.dumpObject(ceFullStrictOtherContentTypeDeserialized, 'ceFullStrictOtherContentTypeDeserialized')}`)
const ceFullTextDataDeserialized = CloudEvent.deserializeEvent(ceFullTextDataSerialized, valOnlyValidInstance)
assert(ceFullTextDataDeserialized !== null)
assert(ceFullTextDataDeserialized.isValid())
assert(!ceFullTextDataDeserialized.isStrict)
assert(CloudEvent.isCloudEvent(ceFullTextDataDeserialized))
console.log(`ce dump: ${T.dumpObject(ceFullTextDataDeserialized, 'ceFullTextDataDeserialized')}`)
const ceFullStrictBinaryDataDeserialized = CloudEvent.deserializeEvent(ceFullStrictBinaryDataSerialized, valOnlyValidInstance)
assert(ceFullStrictBinaryDataDeserialized !== null)
assert(ceFullStrictBinaryDataDeserialized.isValid())
assert(ceFullStrictBinaryDataDeserialized.isStrict)
assert(CloudEvent.isCloudEvent(ceFullStrictBinaryDataDeserialized))
console.log(`ce dump: ${T.dumpObject(ceFullStrictBinaryDataDeserialized, 'ceFullStrictBinaryDataDeserialized')}`)
// then use (validate/send/store/etc) deserialized instances ...
// example usage of some CloudEvent instances as a JSONBatch
// note that I put even wrong data types inside the array to show some features
console.log('\nJSONBatch examples:')
const batch = [
undefined,
null,
'string', // bad
1234567890, // bad
3.14159, // bad
false, // bad
true, // bad
ceMinimalBadSource, // good but not for strict validation
ceMinimal,
ceFull,
new Date(), // bad
{}, // bad
[], // bad
ceFullStrict,
ceErrorStrict,
ceFullStrictOtherContentType, // good, but to serialize/deserialize related options must be used
ceFullTextData,
ceFullStrictBinaryData,
null,
undefined
]
assert(JSONBatch.isJSONBatch(batch))
assert(!JSONBatch.isValidBatch(batch)) // it has some validation error (on its content)
console.log(`JSONBatch contains ${batch.length} items, but only some are valid CloudEvent instances, see related sample code:`)
console.log(`CloudEvent instances valid: ${JSONBatch.getEvents(batch, { ...valOnlyValidInstance, strict: false }).length}`)
console.log(`CloudEvent instances valid in strict mode: ${JSONBatch.getEvents(batch, { ...valOnlyValidInstance, strict: true }).length}`)
// sample validation, in normal and in strict mode
console.log(`JSONBatch validation errors, num: ${JSONBatch.validateBatch(batch, valOptionsNoStrict).length}`)
console.log(`JSONBatch validation errors in strict mode, num: ${JSONBatch.validateBatch(batch, valOptionsStrict).length}`)
console.log(`JSONBatch validation errors in strict mode, details:\n${JSONBatch.validateBatch(batch, valOptionsStrict)}\n`)
assert(JSONBatch.validateBatch(batch, valOptionsNoStrict).length === 8) // expected validation errors
assert(JSONBatch.validateBatch(batch, valOptionsStrict).length === 13) // expected validation errors
// sample filtering of events
// console.log(`DEBUG | JSONBatch.getEvents, num: ${JSONBatch.getEvents(batch, { ...valOnlyValidInstance, strict: true }).length}`)
assert(JSONBatch.getEvents(batch, { ...valOnlyValidAllInstance, strict: false }).length === 8) // no filtering
assert(JSONBatch.getEvents(batch, { ...valOnlyValidAllInstance, strict: true }).length === 8) // no filtering (neither in strict mode)
assert(JSONBatch.getEvents(batch, { ...valOnlyValidInstance, strict: false }).length === 8) // only valid
assert(JSONBatch.getEvents(batch, { ...valOnlyValidInstance, strict: true }).length === 7) // only valid in strict mode
console.log('JSONBatch events: get only valid instances, as a sample')
const events = JSONBatch.getEvents(batch, {
...valOnlyValidInstance,
...valOptionsNoStrict
})
console.log(`JSONBatch events: length = ${events.length}, summary: ${events}`)
console.log(`JSONBatch events: length = ${events.length}, details: ${JSON.stringify(events)}`)
assert(events !== null)
// sample serialization/deserialization on it (batch) or a subset (events)
// note that additional serialization options could be used, for example to handle non default data content types ...
const ser = JSONBatch.serializeEvents(events, { prettyPrint: true, logError: true })
console.log(`JSONBatch events serialized = \n${ser}\n`)
const deser = JSONBatch.deserializeEvents(ser, {
logError: true,
throwError: true,
...valOnlyValidInstance // sample, to filter out not valid serialized instances ...
// onlyIfLessThan64KB: true
})
console.log(`JSONBatch events: deserialized length = ${deser.length}, summary: ${deser}`)
console.log(`JSONBatch events: deserialized JSONBatch length = ${deser.length}, details: ${JSON.stringify(deser)}`)
assert(deser !== null)
// other ...
console.log('\nSample script: end execution.')
console.log('----')
assert(true) // all good here
// end of script