How to perform jsonschemavalidation through http? - javascript

I have defined a restservice and trying to do a jsonschema validation with paperwork:
var _ = require('underscore');
var validate = require('isvalid-express');
var paperwork=require('paperwork');
module.exports = function (app) {
app.post('/myroute', paperwork({
username: /[a-z0-9]+/,
password: String,
age: Number,
interests: [String],
jobs: [{
company: String,
role: String
}]
}, function (req, res) {
// ...
}));
};
This is the request I post this in postman to myroute:
{
username: 'brucewayne',
password: 'iambatman',
age: 36,
interests: ['Climbing', 'CQC', 'Cosplay'],
jobs: [{
company: 'Wayne Inc.',
role: 'CEO'
}]
}
However it throws an error:
TypeError: undefined is not a function
at module.exports (c:\heroku\newher\node_codechallenge\node_modules\paperwork\paperwork.js:129:5)
at module.exports (c:\heroku\newher\node_codechallenge\app\testroutes.js:12:26)
at Object.<anonymous> (c:\heroku\newher\node_codechallenge\test.js:16:31)
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 Module.runMain [as _onTimeout] (module.js:497:10)
at Timer.listOnTimeout [as ontimeout] (timers.js:112:15)
What is the best way of doing a json schemavalidation for http in node.js?

You may consider using JSON-schema standard rather than non-standard schema definition that paperwork uses.
There are many JavaScript JSON Schema validators, here is the benchmark: https://github.com/ebdrup/json-schema-benchmark

Related

i can't a create a model in NodeJS

when i try to create a model in NodeJS
const mongoose = require ('mongoose');
const User = mongoose.model('User',{
name:{
type:string
},
lastname:{
type:string
},
age: {
type:Number
}
})
module.exports = User;
**errorIS
**
C:\Users\models\user.js:6
type:string
^
ReferenceError: string is not defined
at Object.<anonymous> (C:\Users\moham\Desktop\backend\models\user.js:6:14)
at Module._compile (node:internal/modules/cjs/loader:1159:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1213:10)
at Module.load (node:internal/modules/cjs/loader:1037:32)
at Module._load (node:internal/modules/cjs/loader:878:12)
at Module.require (node:internal/modules/cjs/loader:1061:19)
at require (node:internal/modules/cjs/helpers:103:18)
at Object.<anonymous> (C:\Users\moham\Desktop\backend\server.js:2:14)
at Module._compile (node:internal/modules/cjs/loader:1159:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1213:10)
Node.js v18.12.1
The error message is saying that the variable "string" is not defined. In Mongoose, when creating a model, the data types for the fields are typically specified as strings, not by using the JavaScript keyword "string". To fix this, you can change the following line:
name:{ type:string }, lastname:{ type:string }
to:
name:{ type:String }, lastname:{ type:String }
This should resolve the "ReferenceError: string is not defined" error.

'classifierType is not a constructor'

I'm using the limdu library found here (https://www.npmjs.com/package/limdu#binary-classification). I'm trying to combine the 'Multi-Label Classification' section with the 'Input Normalization' section to make the outputs all be lowercase, but I keep getting the following error:
/Users/nickbrinsmade/Desktop/limdutest/node_modules/limdu/classifiers/EnhancedClassifier.js:43
this.classifier = new opts.classifierType();
^
TypeError: opts.classifierType is not a constructor
at new EnhancedClassifier (/Users/myusr/Desktop/limdutest/node_modules/limdu/classifiers/EnhancedClassifier.js:43:20)
at Object.<anonymous> (/Users/myusr/Desktop/limdutest/index.js:9:20)
at Module._compile (internal/modules/cjs/loader.js:1072:14)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1101:10)
at Module.load (internal/modules/cjs/loader.js:937:32)
at Function.Module._load (internal/modules/cjs/loader.js:778:12)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:76:12)
at internal/main/run_main_module.js:17:47
My code Is seen below:
var limdu = require('limdu');
var MyWinnow = limdu.classifiers.Winnow.bind(0, {retrain_count: 10});
var textClassifier = new limdu.classifiers.multilabel.BinaryRelevance({
binaryClassifierType: MyWinnow
});
intentClassifier = new limdu.classifiers.EnhancedClassifier({
classifierType: textClassifier, // same as in previous example
normalizer: limdu.features.LowerCaseNormalizer
}); //this declaration throws the error.
intentClassifier.trainBatch([
{input: {I:1,want:1,an:1,apple:1}, output: "APPLE"},
{input: {I:1,want:1,a:1,banana:1}, output: "BANANA"},
{input: {I:1,want:1,chips:1}, output: "CHIPS"}
]);
console.log(intentClassifier.classify({I:1,want:1,an:1,apple:1,and:1,a:1,banana:1}));

Error trying to run a javascript program from the terminal

I'm trying to run a javascript file prompt.js from the terminal but I'm getting this error.
$ node prompt.js
internal/modules/cjs/loader.js:583
throw err;
^
Error: Cannot find module 'prompt'
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:581:15)
at Function.Module._load (internal/modules/cjs/loader.js:507:25)
at Module.require (internal/modules/cjs/loader.js:637:17)
at require (internal/modules/cjs/helpers.js:22:18)
at Object.<anonymous> (/Users/pathwang/Documents/School/Spring2019/CSC404/CSC404_MyHomework/Patrick_Hwang_CSC404_Hw1/prompt.js:1:77)
at Module._compile (internal/modules/cjs/loader.js:689:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
at Module.load (internal/modules/cjs/loader.js:599:32)
at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
at Function.Module._load (internal/modules/cjs/loader.js:530:3)
This is what is in my prompt.js file:
var prompt = require('prompt');
var schema = {
properties: {
name: {
pattern: /^[a-zA-Z\s\-]+$/,
message: 'Name must be only letters, spaces, or dashes',
required: true
},
email: {
},
exam1: { type: 'number'},
exam2: { type: 'number'},
exam3: { type: 'number'}
}
};
var student = {
name: '',
id: '',
exam1: 60,
exam2: 60,
exam3: 60,
at1: true,
at2: true,
at3: true,
at4: true,
at5: true,
adjust: true,
final: 100,
letter: ' '
};
//
// Get two properties from the user: username and email
//
prompt.get(schema, function (err, result) {
//
// Log the results.
//
console.log('Command-line input received:');
console.log(' username: ' + result.username);
console.log(' email: ' + result.email);
console.log(' exam1:', result.exam1);
console.log(' exam2:', result.exam2);
console.log(' exam3:', result.exam3);
var totalExam;
totalExam = (1/3) * (result.exam1 +
result.exam2 +
result.exam3);
console.log(' Average exam =', totalExam )
});
//
// Start the prompt
//
prompt.start();
I'm in the right directory and I can run other files in the project folder by using $ node test.js. I also can open prompt.js file from the terminal in a different project folder where I copied the source code from. I don't know why this is happening? I would appreciate the help thanks.
The line var prompt = require('prompt'); causing the error. The error is saying it can't find said module. Or the module is not part of the project it doesn't exist. The solution is to find the module called prompt and add the directory into the project folder. This will solve the problem.

nodeJS syntaxError: unexpected token this

Background: User inputs details about a flight in app.js, which then prints it out in the console. Only one module is used from index.js, which contains an object prototype.
Problem: When I run the command "node app.js", I get the following error:
/Users/
UserName/Desktop/NodeTrainingWork/04/objectcreat/flight/index.js:3
var this.data = {
^^^^
SyntaxError: Unexpected token this
at exports.runInThisContext (vm.js:53:16)
at Module._compile (module.js:413:25)
at Object.Module._extensions..js (module.js:452:10)
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)
at Module.require (module.js:365:17)
at require (module.js:384:17)
at Object.<anonymous> (/Users/UserName/Desktop/NodeTrainingWork/04/objectcreat/app.js:1:76)
at Module._compile (module.js:434:26)
at Object.Module._extensions..js (module.js:452:10)
This is the index.js code:
var Flight = function() {
var this.data = {
number: null,
origin: null,
destination: null,
arrivalTime: null
};
this.fill = function(info) {
for (var prop in this.data) {
if (this.data[prop] != 'undefined') {
this.data[prop] = info[prop];
}
}
};
this.triggerArrival: function() {
this.data.arrivalTime = Date.now();
}
this.getInformation: function() {
return this.data;
}
};
module.exports = function(info) {
var instance = new Flight();
instance.fill(info);
return instance;
};
And this is the code in the app.js file:
var flight = require('./flight');
var pdxlax = {
number: 847,
origin: 'PDX',
destination: 'LAX'
};
var pl = flight(pdxlax);
pl.triggerArrival();
console.log(pl.getInformation());
var pk340 = {
number: 340,
origin: 'ISL',
destination: 'DXB'
};
var pk = flight(pk340);
pk.triggerArrival();
console.log(pk.getInformation());
I dont know where I am going wrong. From what I have learned, my way of creating a an object prototype is correct.
var is used to create a new variable, not to create a property on an object.
Remove var from the line that is erroring.

Node mustache rendering server side

I'm trying to create a simple application to compile mustache templates into static pages server side, here's what I've got so far:
var view = {
title: "Joe",
calc: function () {
return 2+4;
}
};
var mustache = require("mustache");
var template = require("./home.template");
var output = mustache.to_html(template, view);
console.log(output);
And my template looks like:
{{title}} spend {{calc}}
Any suggestions as to what is causing this to fail?
Here is the complete error message:
home.template:1
} spend {{calc}}
^
module.js:437
var compiledWrapper = runInThisContext(wrapper, filename, true);
^
SyntaxError: Unexpected token {
at Module._compile (module.js:437:25)
at Object.Module._extensions..js (module.js:467:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.require (module.js:362:17)
at require (module.js:378:17)
at Object.<anonymous> (/Users/MorehouseJ09/Documents/production_development/mustache/current/compiler.js:12:16)
at Module._compile (module.js:449:26)
at Object.Module._extensions..js (module.js:467:10)
at Module.load (module.js:356:32)
Any help would be great!
Use fs.readFile() to read your template in as a string. Require won't work unless it's requiring javascript code, not mustache code.
http://nodejs.org/api/fs.html#fs_fs_readfile_filename_encoding_callback
Edit
See if this works...
var mustache = require("mustache");
var fs = require("fs");
var view = {
title: "Joe",
calc: function () {
return 2+4;
}
};
fs.readFile('./home.template', 'utf-8', function (err, data) {
if (err) throw err;
var output = mustache.to_html(data, view);
console.log(output);
});

Categories