AJV schema validation fails - node.js

I am using Jsonix, I have used below mentioned command to generate jsonix mapping and jsonix schema as,
java -jar jsonix-schema-compiler-full.jar -generateJsonSchema -d mappings books.xsd
it is properly generating mapping and schema, I want to validate JSON using AJV and the generated JSON Schema, so I have tried this,
var fs = require('fs');
var Ajv = require('ajv');
var XMLSchemaJsonSchema = JSON.parse(fs.readFileSync('../node_modules/jsonix/jsonschemas/w3c/2001/XMLSchema.jsonschema').toString());
var JsonixJsonSchema = JSON.parse(fs.readFileSync('../node_modules/jsonix/jsonschemas/jsonix/Jsonix.jsonschema').toString());
var booksJsonSchema = JSON.parse(fs.readFileSync('./books.jsonschema').toString());
var ajv = new Ajv();
ajv.addSchema(XMLSchemaJsonSchema, 'http://www.jsonix.org/jsonschemas/w3c/2001/XMLSchema.jsonschema');
ajv.addSchema(JsonixJsonSchema, 'http://www.jsonix.org/jsonschemas/jsonix/Jsonix.jsonschema');
var validate = ajv.compile(booksJsonSchema);
var data ={
"book": [
{
"#id": "bk001",
"author": "Writer",
"title": "The First Book",
"genre": "Fiction",
"price": "44.95",
"pub_date":2000-10-01,
"review": "An amazing story of nothing."
},
{
"#id": "bk002",
"author": "Poet",
"title": "The Poet's First Poem",
"genre": "Poem",
"price": "24.95",
"pub_date":2000-10-02,
"review": "Least poetic poems."
}
]
};
var valid = validate(data);
if (!valid) {
console.log('Validation failed errors:');
console.log(validate.errors);
}else{
console.log("successfully done validation");
}
But it is throwing error
/Users/qliktag/Desktop/QAGG/qagUI2/Scripts/QLIKTAG-2602/node_modules/ajv/lib/ajv.js:183
else throw new Error(message);
^
Error: schema is invalid: data.definitions['nonPositiveInteger'].anyOf[0].exclusiveMaximum should be number
at Ajv.validateSchema (/Users/qliktag/Desktop/QAGG/qagUI2/testScripts/node_modules/ajv/lib/ajv.js:185:16)
at Ajv._addSchema (/Users/qliktag/Desktop/QAGG/qagUI2/Scripts/QLIKTAG-2602/node_modules/ajv/lib/ajv.js:316:10)
at Ajv.addSchema (/Users/qliktag/Desktop/QAGG/qagUI2/Scripts/QLIKTAG-2602/node_modules/ajv/lib/ajv.js:136:29)
at Object.<anonymous> (/Users/qliktag/Desktop/QAGG/qagUI2/Scripts/QLIKTAG-2602/mappings/ajvSample.js:248:5)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
Actually the error comes while ajv addschema, Is I did anything wrong?

To continue using draft-04 schemas added meta: false to prevent adding draft-06 meta-schema https://github.com/epoberezkin/ajv/releases/tag/5.0.0
var ajv = new Ajv({
schemaId: 'id',
meta: false,
});
var metaSchema = require('../node_modules/ajv/lib/refs/json-schema-draft-04.json');
ajv.addMetaSchema(metaSchema);
ajv._opts.defaultMeta = metaSchema.id;
ajv._refs['http://json-schema.org/schema'] = 'http://json-schema.org/draft-04/schema';
After adding this use addSchema to allow booleans for exclusiveMaximum
ajv.addSchema(XMLSchemaJsonSchema, 'http://www.jsonix.org/jsonschemas/w3c/2001/XMLSchema.jsonschema');
ajv.addSchema(JsonixJsonSchema, 'http://www.jsonix.org/jsonschemas/jsonix/Jsonix.jsonschema');

The change of exclusiveMaximum from boolean to number happened with Draft-06/07 of JSON Schema.
// var ajv = new Ajv({schemaId: 'id'});
// If you want to use both draft-04 and draft-06/07 schemas:
var ajv = new Ajv({schemaId: 'auto'});
ajv.addMetaSchema(require('ajv/lib/refs/json-schema-draft-04.json'));
Use this and then addSchema to allow booleans for exclusiveMaximum
ajv.addSchema(XMLSchemaJsonSchema, 'http://www.jsonix.org/jsonschemas/w3c/2001/XMLSchema.jsonschema');
ajv.addSchema(JsonixJsonSchema, 'http://www.jsonix.org/jsonschemas/jsonix/Jsonix.jsonschema');

Author of Jsonix here.
As it is pointed out in the documentation, JSON Schema generation is an experimental feature. So it would be not surprizing that it fails. You are welcome to file issues.

Related

AWS CDK: There can only be one default behavior across all sources

Background
I have a piece of cdk code that runs in a function. Each time through it creates a cloud front distribution. I want one instance to have a different value of behavior. This seems like a very simple thing, but I always get the error below that I do not understand.
Code
// 1. Default:
let behavior: cloudfront.Behavior = {isDefaultBehavior: true};
// Lambda Edge / Cloudfront Function Authentication...
if (subDomain == "monkey-ops") {
// 2. Cloudfront Function.
const cfFunct = new cloudfront.Function(this, 'id', {
functionName: 'http-auth-ops',
comment: 'http-auth for monkey-ops.monkeytronics.co.nz static site',
code: cloudfront.FunctionCode.fromFile({filePath: __dirname + '\\http-auth-ops-cf.js'})
});
behavior = {
isDefaultBehavior: false,
functionAssociations: [{
eventType: cloudfront.FunctionEventType.VIEWER_REQUEST,
function: cfFunct
}]
};
// behavior = {isDefaultBehavior: true};
} else {
behavior = {isDefaultBehavior: true};
}
let cloudFrontDistribution = new cloudfront.CloudFrontWebDistribution(this, subDomain + 'Distribution', {
originConfigs: [
{
customOriginSource: {
domainName: s3Bucket.bucketWebsiteDomainName,
originProtocolPolicy: cloudfront.OriginProtocolPolicy.HTTP_ONLY,
},
// behaviors : [ {isDefaultBehavior: true} ],
behaviors : [ behavior ],
}
],
viewerCertificate: cloudfront.ViewerCertificate.fromAcmCertificate(
tslCert,
{
aliases: [ subDomain + '.monkeytronics.co.nz' ],
// securityPolicy: cloudfront.SecurityPolicyProtocol.SSL_V3, // default
securityPolicy: cloudfront.SecurityPolicyProtocol.TLS_V1_2_2021,
sslMethod: cloudfront.SSLMethod.SNI, // default
},
),
});
Error
Gives the following error, which I can't unpick...
Error: There can only be one default behavior across all sources. [ One default behavior per distribution ].
at new CloudFrontWebDistribution (D:\MonkeySource\2-Cloud\cdk_stacks\node_modules\aws-cdk-lib\aws-cloudfront\lib\web-distribution.js:1:6631)
at new StaticSite (D:\MonkeySource\2-Cloud\cdk_stacks\lib\factory\static-site\static-site-factory.ts:120:42)
at new SnWebStack (D:\MonkeySource\2-Cloud\cdk_stacks\lib\sn-web-stack.ts:57:7)
at Object.<anonymous> (D:\MonkeySource\2-Cloud\cdk_stacks\bin\cdk.ts:19:1)
at Module._compile (node:internal/modules/cjs/loader:1101:14)
at Module.m._compile (D:\MonkeySource\2-Cloud\cdk_stacks\node_modules\ts-node\src\index.ts:1056:23)
at Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
at Object.require.extensions.<computed> [as .ts] (D:\MonkeySource\2-Cloud\cdk_stacks\node_modules\ts-node\src\index.ts:1059:12)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
Subprocess exited with error 1
The error message is misleading. You are getting it because you have no default behavior configured.
{
isDefaultBehavior: true, // <-- This needs to be true for one behavior
functionAssociations: [{
eventType: cloudfront.FunctionEventType.VIEWER_REQUEST,
function: cfFunct
}]
}
It means that you need to have only single default behavior.
But you can add multiple behaviors.
Cloudfront let's you create multiple behaviors and origins, which then can be used for multiple purposes.
Check the examples here
https://kuchbhilearning.blogspot.com/2022/10/add-cloudfront-behavior-and-origin.html
https://kuchbhilearning.blogspot.com/2022/10/api-gateway-and-cloud-front-in-same.html

Error [FirebaseError]: Invalid document reference. Document references must have an even number of segments [duplicate]

This question already has an answer here:
Error [FirebaseError]: Invalid document reference. Document references must have an even number of segments,
(1 answer)
Closed 2 years ago.
const firebase = require("firebase");
// Required for side-effects
require("firebase/firestore");
// Initialize Cloud Firestore through Firebase
firebase.initializeApp({
apiKey: "____",
authDomain: "____",
projectId: "____"
});
var db = firebase.firestore();
var datasetSymptom=[{
"Disease" : [ "edema pulmonary" ],
"Symptom" : "Heberden's node"
}, {
"Disease" : [ "cholecystitis" ],
"Symptom" : "Murphy's sign"
}, {
"Disease" : [ "hemiparesis", "hypertension pulmonary", "transient ischemic attack" ],
"Symptom" : "Stahli's line"
}
]
datasetSymptom.forEach(function(obj) {
db.collection("datasetSymptom").doc(obj.Symptom).set({
Disease: obj.Disease
})
});
I already ran the same algo on another collection with same Disease name as doc and array of symptoms as field. It worked fine.
Error:
D:\react tutorial\reactnative\fyp\node_modules\#firebase\firestore\dist\node-cjs\database-21da52c3-e2da0fdd.js:25868
throw replaceFunctionName(e, 'doc()', 'CollectionReference.doc()');
^
Error [FirebaseError]: Invalid document reference. Document references must have an even number of segments, but datasetSymptom/feels hot/feverish has 3.
at new FirestoreError (D:\react tutorial\reactnative\fyp\node_modules\←[4m#firebase←[24m\firestore\dist\node-cjs\database-21da52c3-e2da0fdd.js:209:28)
at validateDocumentPath (D:\react tutorial\reactnative\fyp\node_modules\←[4m#firebase←[24m\firestore\dist\node-cjs\database-21da52c3-e2da0fdd.js:19706:15)
at doc (D:\react tutorial\reactnative\fyp\node_modules\←[4m#firebase←[24m\firestore\dist\node-cjs\database-21da52c3-e2da0fdd.js:22462:9)
at CollectionReference$1.doc (D:\react tutorial\reactnative\fyp\node_modules\←[4m#firebase←[24m\firestore\dist\node-cjs\database-21da52c3-e2da0fdd.js:25864:64)
at D:\react tutorial\reactnative\fyp\index2x2.js:1233:37
at Array.forEach (<anonymous>)
at Object.<anonymous> (D:\react tutorial\reactnative\fyp\index2x2.js:1231:16)
←[90m at Module._compile (internal/modules/cjs/loader.js:1063:30)←[39m
←[90m at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)←[39m
←[90m at Module.load (internal/modules/cjs/loader.js:928:32)←[39m {
code: ←[32m'invalid-argument'←[39m,
toString: ←[36m[Function (anonymous)]←[39m
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Solved by searching for symptom containing '/' as that is invalid i replaced it with '-' it solved my problem –

Error [FirebaseError]: Invalid document reference. Document references must have an even number of segments,

const firebase = require("firebase");
// Required for side-effects
require("firebase/firestore");
// Initialize Cloud Firestore through Firebase
firebase.initializeApp({
apiKey: "____",
authDomain: "____",
projectId: "____"
});
var db = firebase.firestore();
var datasetSymptom=[{
"Disease" : [ "edema pulmonary" ],
"Symptom" : "Heberden's node"
}, {
"Disease" : [ "cholecystitis" ],
"Symptom" : "Murphy's sign"
}, {
"Disease" : [ "hemiparesis", "hypertension pulmonary", "transient ischemic attack" ],
"Symptom" : "Stahli's line"
}
]
datasetSymptom.forEach(function(obj) {
db.collection("datasetSymptom").doc(obj.Symptom).set({
Disease: obj.Disease
})
});
I already ran the same algo on another collection with same Disease name as doc and array of symptoms as field. It worked fine.
Error:
D:\react tutorial\reactnative\fyp\node_modules\#firebase\firestore\dist\node-cjs\database-21da52c3-e2da0fdd.js:25868
throw replaceFunctionName(e, 'doc()', 'CollectionReference.doc()');
^
Error [FirebaseError]: Invalid document reference. Document references must have an even number of segments, but datasetSymptom/feels hot/feverish has 3.
at new FirestoreError (D:\react tutorial\reactnative\fyp\node_modules\←[4m#firebase←[24m\firestore\dist\node-cjs\database-21da52c3-e2da0fdd.js:209:28)
at validateDocumentPath (D:\react tutorial\reactnative\fyp\node_modules\←[4m#firebase←[24m\firestore\dist\node-cjs\database-21da52c3-e2da0fdd.js:19706:15)
at doc (D:\react tutorial\reactnative\fyp\node_modules\←[4m#firebase←[24m\firestore\dist\node-cjs\database-21da52c3-e2da0fdd.js:22462:9)
at CollectionReference$1.doc (D:\react tutorial\reactnative\fyp\node_modules\←[4m#firebase←[24m\firestore\dist\node-cjs\database-21da52c3-e2da0fdd.js:25864:64)
at D:\react tutorial\reactnative\fyp\index2x2.js:1233:37
at Array.forEach (<anonymous>)
at Object.<anonymous> (D:\react tutorial\reactnative\fyp\index2x2.js:1231:16)
←[90m at Module._compile (internal/modules/cjs/loader.js:1063:30)←[39m
←[90m at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)←[39m
←[90m at Module.load (internal/modules/cjs/loader.js:928:32)←[39m {
code: ←[32m'invalid-argument'←[39m,
toString: ←[36m[Function (anonymous)]←[39m
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
It looks like one or more of the objects in your array don't have a Symptom property. When that happens doc(obj.Symptom) results in a reference to an empty document, which is what causes the error.
To find the problematic array item, either check your JSON manually, or do something like this in your code:
datasetSymptom.forEach(function(obj, index) {
if (obj.Symptom && object.Symptom.length) {
db.collection("datasetSymptom").doc(obj.Symptom).set({
Disease: obj.Disease
})
}
else {
console.error(`Found an object without a Symptom at index ${index} in the array`);
}
});

Runtime.ImportModuleError Error: Cannot find module 'axios/lib/utils' Serverless

I am using the Serverless framework. Backend as node.js. I have several microservices and all others are working fine, but now I have created now microservice where I have not used Axios but still, it is throwing error in the console.
One more issue is that in my local system it works perfectly, but as I push the same into the server then it starts creating issues.
This is the sample code which is throwing error
const { IamAuthenticator } = require('ibm-watson/auth');
const NaturalLanguageUnderstandingV1 = require('ibm-watson/natural-language-understanding/v1');
async function textAnalyse(req, res) {
const naturalLanguageUnderstanding = new NaturalLanguageUnderstandingV1({
version: '2019-07-12',
authenticator: new IamAuthenticator({
apikey: 'API KEY'
}),
url: 'https://URL/natural-language-understanding/api'
});
const analyzeParams = {
'text': HtmlToText.fromString('Test text here'),
'features': {
'entities': {
'sentiment': true,
'limit': 100
}
}
};
const analysis = await naturalLanguageUnderstanding.analyze(analyzeParams);
// prepare the response object
res.send({ analysis: analysis });
}
Error in AWS Cloud watch
{
"errorType": "Runtime.ImportModuleError",
"errorMessage": "Error: Cannot find module 'axios/lib/utils'",
"stack": [
"Runtime.ImportModuleError: Error: Cannot find module 'axios/lib/utils'",
" at _loadUserApp (/var/runtime/UserFunction.js:100:13)",
" at Object.module.exports.load (/var/runtime/UserFunction.js:140:17)",
" at Object.<anonymous> (/var/runtime/index.js:45:30)",
" at Module._compile (internal/modules/cjs/loader.js:778:30)",
" at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)",
" at Module.load (internal/modules/cjs/loader.js:653:32)",
" at tryModuleLoad (internal/modules/cjs/loader.js:593:12)",
" at Function.Module._load (internal/modules/cjs/loader.js:585:3)",
" at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)",
" at startup (internal/bootstrap/node.js:283:19)",
" at bootstrapNodeJSCore (internal/bootstrap/node.js:623:3)"
]
}
I found the fixes for this.
when we call third-party API from our Lambda it requires the Axios to be implemented internally. So you need to create a folder that will have a package.json file with the dependency
"dependencies": {
"axios": "^0.19.2"
}
Then add the layer in the functions from AWS UI, left side menu
Then add the layer to your function
Now, by doing the above activity the issue will be resolved and Axios dependency is added successfully individually to the microservice.
Also, what you name the folders matters before zipping. Review these AWS docs for folder naming so you can import the library like you would in any other project.
https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html

".then is not a function" from a very simple inquirer program

the very simple example below (pretty much copied off the npm inquirer front page) is giving the ".then is not a function" error. However I can't figure out what the issue is.
var inquirer = require('inquirer');
inquirer.prompt([
{
name: 'my_name',
type: 'input',
message: 'What is your name: '
}]).then(answers => {
console.log("Your name is:"+answers.my_name)
});
The error message looks like this:
? What is your name:
/home/peter/Documents/nodejs.d/vscode_examples_workspace/security/inq.js:8
}]).then(answers => {
^
TypeError: inquirer.prompt(...).then is not a function
at Object.<anonymous> (/home/peter/Documents/nodejs.d/vscode_examples_workspace/security/inq.js:8:13)
at Module._compile (internal/modules/cjs/loader.js:654:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:665:10)
at Module.load (internal/modules/cjs/loader.js:566:32)
at tryModuleLoad (internal/modules/cjs/loader.js:506:12)
at Function.Module._load (internal/modules/cjs/loader.js:498:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:695:10)
at startup (internal/bootstrap/node.js:201:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:516:3)
But the following example works OK. So the basic node.js environment (nodejs --version = v9.11.2) is OK.
var inquirer = require('inquirer');
let q = [
{
name: 'my_name',
type: 'input',
message: 'What is your name: '
}];
inquirer.prompt (q, function (answers){
console.log("Your name is: "+answers.my_name);
});
// Output
$ nodejs inq.js
? What is your name: Peter
Your name is: Peter
This is probably because you have an old version of inquirer (0.12.0 or older) which does not support promises (promises were added in version 1.0.0).
Your snippet works fine with version 6.0.0 and 1.0.0 but fails with the exact same error message in version 0.12.0.
Check packages.json for your version and update it:
"dependencies": {
"inquirer": "^6.0.0"
}
Then do
npm install

Resources