sequelize validation method - validation

I'm trying to validate my Model but i miss something and i don't know what is it.
It is my module and his validation for email.
module.exports = function(sequelize, DataTypes){
return sequelize.define("Scanner",
{
id : {
primaryKey : true,
autoIncrement : true,
type : DataTypes.INTEGER
},
email : {
type : DataTypes.STRING,
isUnique :true,
allowNull:false,
validate:{
isEmail : true
}
},
pin : {
type : DataTypes.INTEGER
}
},{
tableName : 'scanner'
});
};
When i'm trying to Find an object with parameters (pin + email) if i put this.email = ssdf.sdf , my query is launched and i would like to check first if my params are correct.
Scanner.prototype.getScannerByCredentials = function(callback){
//Send only Field id and email
_Scanner.find({ where: { email : this.email, pin :this.pin},attributes:['id','email'] }).success(function(scanner) {
return callback(null, scanner);
}).error(function(error){
console.log(error);
return callback(error, null);
});
};
I tried with validate() method but i've got as error : Object [object Object] has no method 'validate' and when i'm made a console.log(_Scanner); i saw my function validate() so i don't know why that's doesn't work..
Scanner.prototype.getScannerByCredentials = function(callback){
//Send only Field id and email
_Scanner.find({ where: { email : this.email, pin :this.pin},attributes:['id','email'] }).validate().success(function(scanner) {
return callback(null, scanner);
}).error(function(error){
console.log(error);
return callback(error, null);
});
};
I'm reading the docs and try a lot of thing founded on the net so if someone could explain to me what's wrong, it will be really nice.
Thanks a lot in advance.
EDIT : FOUND !
My solution if you're interested :)
My Models :
module.exports = function(sequelize, DataTypes){
return sequelize.define("Scanner",
{
id : {
primaryKey : true,
autoIncrement : true,
type : DataTypes.INTEGER,
allowNull : false
},
email : {
type : DataTypes.STRING,
isUnique :true,
allowNull:false,
validate:{
isEmail : true
}
},
pin : {
type : DataTypes.INTEGER
}
},{
tableName : 'scanner',
classMethods:{
isValid : function(objScanner) {
return this.build(objScanner).validate() ? true : false ;
}
}
});
};
My credentials Method :
Scanner.prototype.getScannerByCredentials = function(callback){
//MODIF THIS PART / NEED TO IMPROVE
var error = _Scanner.build({ email : this.email, pin : this.pin}).validate();
if(error === null){
_Scanner.find({ where: { email : this.email, pin :this.pin},attributes:['id','email'] }).success(function(scanner) {
console.log(scanner);
return callback(null, scanner);
}).error(function(error){
console.log(error);
return callback(error, null);
});
}
else
return callback(error,null);
};
And my generic update method (bonus) :
Scanner.prototype.update= function(callback){
var self = this;
_Scanner.find(this.id).success(function(scannerFound){
if(scannerFound){
//Set old Values by New Values : only values changed
scannerFound.dataValues = ormize(self,scannerFound.dataValues);
//Check validation Fields before insert DB
if(_Scanner.isValid(scannerFound)){
scannerFound.save().success(function(){
return callback(true);
}).error(function(error){
return callback(false);
});
}else
return callback(false);
}else
return callback(false);
}).error(function(error){
console.log(error);
return callback(false);
});
};
If you have any advice with my code it will be grateful too :)
Thank a lot in advance

What version do you use? This should have been fixed
The field should look like this.
isEmail: {msg: 'Reason'}

Related

Sequelize check row exists, and return boolean

I am attempting to use Sequelize to query an association table to see if one user is following another. If the relationship exists, I want to return true. If not, return false. I want to return this response to the "following" section of toProfileJSONFor (see below).
Based on logging, everything seems to be working as expected, except I receive a promise back instead of my boolean value. I've read up as much as I can find on promises, but still can't seem to figure out my issue.
Here is the result that I am currently receiving:
{
"profile": {
"username": "superman1",
"bio": null,
"image": "",
"following": {
"isFulfilled": false,
"isRejected": false
}
}
}
I understand that this is a problem with promises, but I cannot figure out a resolution.
User.prototype.toProfileJSONFor = function(user){
return {
username: this.username,
bio: this.bio,
image: this.image || 'genericImage.jpg',
following: user.isFollowing(this.id) //this is where I am having issues
};
User.prototype.isFollowing = function(id){
let userId = this.id; // current userId
let followId = id; //profile Id
return FollowerFolloweds.findAll({
where: { followedId: followId, followerId: userId},raw : true })
.then(function(result) {
if(result.length !=0){
return true;
} {
return false;
}
})
}
The expected result would be:
{
"profile": {
"username": "superman1",
"bio": null,
"image": "",
"following": true
}
}
Try the following:
User.prototype.toProfileJSONFor = function(user){
return user.isFollowing(this.id)
.then((following) => {
username: this.username,
bio: this.bio,
image: this.image || 'genericImage.jpg',
following
});
}

ASK error, TypeError: Cannot read property 'type' of undefined

I'm creating a skill that will call back different incidents at different dates and times from a DynamoDB table through Alexa.
My 3 columns are data, time and incident
I've defined my partition and sort key in my Lambda function as
let GetMachineStateIntent = (context, callback) => {
var params = {
TableName: "updatedincident",
Key: {
date: "2017-03-21",
time: "07:38",
incident: "Blocked Primary",
}
};
When I try to test my skill I can't seem to recall the incident correctly, the error I'm getting in Cloudwatch is:
2018-03-28T14:48:53.397Z 042319cb-4a3e-49ae-8b33-1641367107d4 Unexpected error occurred in the skill handler! TypeError: Cannot read property 'type' of undefined
at exports.handler.e (/var/task/index.js:70:16)
as well as:
2018-03-28T14:48:53.417Z 042319cb-4a3e-49ae-8b33-1641367107d4
{
"errorMessage": "Unexpected error"
}
Here is my code from index.js
var AWSregion = 'us-east-1'; // us-east-1
var AWS = require('aws-sdk');
var dbClient = new AWS.DynamoDB.DocumentClient();
AWS.config.update({
region: "'us-east-1'"
});
let GetMachineStateIntent = (context, callback) => {
var params = {
TableName: "updatedincident",
Key: {
date: "2018-03-28",
time: "04:23",
}
};
dbClient.get(params, function (err, data) {
if (err) {
// failed to read from table for some reason..
console.log('failed to load data item:\n' + JSON.stringify(err, null, 2));
// let skill tell the user that it couldn't find the data
sendResponse(context, callback, {
output: "the data could not be loaded from your database",
endSession: false
});
} else {
console.log('loaded data item:\n' + JSON.stringify(data.Item, null, 2));
// assuming the item has an attribute called "incident"..
sendResponse(context, callback, {
output: data.Item.incident,
endSession: false
});
}
});
};
function sendResponse(context, callback, responseOptions) {
if(typeof callback === 'undefined') {
context.succeed(buildResponse(responseOptions));
} else {
callback(null, buildResponse(responseOptions));
}
}
function buildResponse(options) {
var alexaResponse = {
version: "1.0",
response: {
outputSpeech: {
"type": "SSML",
"ssml": `<speak><prosody rate="slow">${options.output}</prosody></speak>`
},
shouldEndSession: options.endSession
}
};
if (options.repromptText) {
alexaResponse.response.reprompt = {
outputSpeech: {
"type": "SSML",
"ssml": `<speak><prosody rate="slow">${options.reprompt}</prosody></speak>`
}
};
}
return alexaResponse;
}
exports.handler = (event, context, callback) => {
try {
var request = event.request;
if (request.type === "LaunchRequest") {
sendResponse(context, callback, {
output: "welcome to my skill. what data are you looking for?",
endSession: false
});
}
else if (request.type === "IntentRequest") {
let options = {};
if (request.intent.name === "GetMachineStateIntent") {
GetMachineStateIntent(context, callback);
} else if (request.intent.name === "AMAZON.StopIntent" || request.intent.name === "AMAZON.CancelIntent") {
sendResponse(context, callback, {
output: "ok. good bye!",
endSession: true
});
}
else if (request.intent.name === "AMAZON.HelpIntent") {
sendResponse(context, callback, {
output: "you can ask me about incidents that have happened",
reprompt: "what can I help you with?",
endSession: false
});
}
else {
sendResponse(context, callback, {
output: "I don't know that one! please try again!",
endSession: false
});
}
}
else if (request.type === "SessionEndedRequest") {
sendResponse(context, callback, ""); // no response needed
}
else {
// an unexpected request type received.. just say I don't know..
sendResponse(context, callback, {
output: "I don't know that one! please try again!",
endSession: false
});
}
} catch (e) {
// handle the error by logging it and sending back an failure
console.log('Unexpected error occurred in the skill handler!', e);
if(typeof callback === 'undefined') {
context.fail("Unexpected error");
} else {
callback("Unexpected error");
}
}
};
and this is my handler GetMachineState.js
function sendResponse(context, callback, responseOptions) {
if(typeof callback === 'undefined') {
context.succeed(buildResponse(responseOptions));
} else {
callback(null, buildResponse(responseOptions));
}
}
function buildResponse(options) {
var alexaResponse = {
version: "1.0",
response: {
outputSpeech: {
"type": "SSML",
"ssml": `<speak><prosody rate="slow">${options.output}</prosody></speak>`
},
shouldEndSession: options.endSession
}
};
if (options.repromptText) {
alexaResponse.response.reprompt = {
outputSpeech: {
"type": "SSML",
"ssml": `<speak><prosody rate="slow">${options.reprompt}</prosody></speak>`
}
};
}
return alexaResponse;
}
exports.handler = (event, context, callback) => {
try {
var request = event.request;
if (request.type === "LaunchRequest") {
sendResponse(context, callback, {
output: "welcome to my skill. what do you want to find?",
endSession: false
});
}
else if (request.type === "IntentRequest") {
let options = {};
if (request.intent.name === "GetMachineStateIntent") {
// this is where we will wire up the dynamo call
// for now, just send a simple response and end the session
sendResponse(context, callback, {
output: "cinema not implemented yet!",
endSession: true
});
} else if (request.intent.name === "AMAZON.StopIntent" || request.intent.name === "AMAZON.CancelIntent") {
sendResponse(context, callback, {
output: "ok. good bye!",
endSession: true
});
}
else if (request.intent.name === "AMAZON.HelpIntent") {
sendResponse(context, callback, {
output: "you can ask me about incidents that have happened",
reprompt: "what can I help you with?",
endSession: false
});
}
else {
sendResponse(context, callback, {
output: "I don't know that one! Good bye!",
endSession: true
});
}
}
else if (request.type === "SessionEndedRequest") {
sendResponse(context, callback, ""); // no response needed
}
else {
// an unexpected request type received.. just say I don't know..
sendResponse(context, callback, {
output: "I don't know that one! Good bye!",
endSession: true
});
}
} catch (e) {
// handle the error by logging it and sending back an failure
console.log('Unexpected error occurred in the skill handler!', e);
if(typeof callback === 'undefined') {
context.fail("Unexpected error");
} else {
callback("Unexpected error");
}
}
};
Its impossible to know for sure if this is the problem or not because you haven't shared the code from the index.js file. The error message you get is telling you that the problem occurs at line 70 in your index.js file so you should look there, and figure out what the problem is.
However, based on the fact that you also posted this as a comment on another question, I'm going to venture to guess that the issue you've run into is that you used the code snippet I provided in the answer to that question and the error is from dereferencing the request.type
You have to make sure the request variable is set to the actual request from the event, like so: var request = event.request where event is provided from exports.handler = (event, context, callback) => {
For example:
exports.handler = (event, context, callback) => {
var request = event.request;
if (request.type === "IntentRequest"
// make suret the name of the intent matches the one in your interaction model
&& request.intent.name == "GetMachineStateIntent") {
var dateSlot = request.intent.slots.Date != null ?
request.intent.slots.Date.value : "unknown date";
var timeSlot = request.intent.slots.Time != null ?
request.intent.slots.Time.value : "unknown time";
// respond with speech saying back what the skill thinks the user requested
sendResponse(context, callback, {
output: "You wanted the machine state at "
+ timeSlot + " on " + dateSlot,
endSession: true
});
} else {
// TODO: handle other types of requests..
sendResponse(context, callback, {
output: "I don't know how to handle this request yet!"
endSession: true
});
}
};
function sendResponse(context, callback, responseOptions) {
if(typeof callback === 'undefined') {
context.succeed(buildResponse(responseOptions));
} else {
callback(null, buildResponse(responseOptions));
}
}
function buildResponse(options) {
var alexaResponse = {
version: "1.0",
response: {
outputSpeech: {
"type": "SSML",
"ssml": `<speak><prosody rate="slow">${options.output}</prosody></speak>`
},
shouldEndSession: options.endSession
}
};
if (options.repromptText) {
alexaResponse.response.reprompt = {
outputSpeech: {
"type": "SSML",
"ssml": `<speak><prosody rate="slow">${options.reprompt}</prosody></speak>`
}
};
}
return alexaResponse;
}

Bookshelf.js lifecycle events not occurring in expected order

My initialize events are not running in the expected order.
I have the following lifecycle event listeners in my Bookshelf model:
initialize: function() {
this.on('saving', this.validate);
this.on('creating', this.generateId);
this.on('creating', this.hashPassword);
this.on('creating', this.generateUsername);
}
I return a Promise in the 'generateUsername' method. According to the logs, this Promise completes after the 'validate' method is run.
I was under the impression that the lifecycle events are Promise-aware and would wait for the Promise to complete before proceeding. What am I doing wrong?
Lifecycle methods:
generateId: function() {
this.set('id', shortid.generate());
},
hashPassword: function() {
/* eslint-disable no-invalid-this */
return bcrypt.genSaltAsync(12).bind(this)
.then(function(salt) {
return bcrypt.hashAsync(this.get('password'), salt);
})
.then(function(hash) {
this.set('password', hash);
});
},
generateUsername: function(model, attr, options) {
var email = this.get('email');
if (!email) {
this.set('username', shortid.generate());
return;
}
var username = email.substring(0, email.indexOf('#')).replace(/[^a-z0-9_-]/g, '');
if (!username) {
this.set('username', shortid.generate());
return;
}
var self = this;
return User.where('username', '=', username)
.fetch()
.then(function(found) {
if (!found) {
self.set('username', username);
winston.info('setting username to [%s]', username);
} else {
self.set('username', username + shortid.generate());
winston.info('setting username to [%s]', self.get('username'));
}
});
},
validate: function() {
return checkit.run(this.attributes);
}
Logs:
info: Validation errors { username: [ 'The username is required' ],
ageGroup: [ 'The ageGroup is required' ],
bodyType: [ 'The bodyType is required' ] }
info: setting username to [nim_sathiVyxIkm--Hx]
The incorrect ordering of events was reported as an issue in Bookshelf and fixed in version 0.13.0 that was released in the 18th of March, 2018, so your code should work as expected now.

ElasticSearch Truncate Index TypeError

I am using mongoosastic npm module. While truncating index I am getting
TypeError: Unable to build a path with those params. Supply at least index
The code I'm using
For Truncate :
var tagModelJS = require('../DaoModel/TagModel.js');
var TagModel = tagModelJS.getTagModel();
TagModel.esTruncate(function (err) {
if (err) {
console.log("ERROR : while removing data from elastic search.")
throw err;
}
});
TagModel :
var TAGS;
module.exports = {
createSchemaAndGetModel : function (mongoose, mongoosastic, Schema) {
//create schema
var tagSchema = new Schema({
tagDetail : String,
userIds : [], //list of user ids
tagName : {
type : [String],
es_indexed : true
} // field level
});
tagSchema.plugin(mongoosastic)
//create model
TAGS = mongoose.model('TAGS', tagSchema);
console.log("Tag model ready....");
},
getTagModel : function () {
return TAGS;
}
};
Any help would be greatly appreciated.

Remove List Item From Array MongoDB

I am creating a node application and storing information in MongoDB using mongoose. I am trying to use a DELETE request to remove a list item from an array stored in mongodb. Each list item is an object, for example:
"budgets" : [
{
"name" : "check",
"value" : 100,
"expense" : false,
"uniqueId" : 0.1224423
},
{
"name" : "bagel",
"value" : 5,
"expense" : true,
"uniqueId" : 0.12424214
}
]
I am sending a paramer in the url which is targeting "uniqueId". I want to remove budgets[1] by tageting it's uniqueId and removing from the list. How would I do this? This is what I am trying but it is not working:
router.delete('/users', function(req, res){
if (req.session.passport.user == undefined){
res.json({success: "false"});
} else{
regUser.findOneAndUpdate(
{ username:req.user.username },
{ $pull: { budgets : { uniqueId: req.param('id') }} },
{new: true},
function(err, data){
if(err) return console.log(err);
res.json(data.budgets);
});
}
});
I want the callback function of regUser.update to return the updated information, but since the information is not being updated it is just returning the original data. So how would I remove the list item containing the "uniqueId" that I pass through as a parameter?
I implemented the findOneAndUpdate method ( thanks Neil Lunn ). I also realized that the problem had to do with the parameter I was passing in the URL. In my list the uniqueId is a floating point number, but I was getting a String. So I passed the parameter into the parse
router.delete('/users', function(req, res){
if (req.session.passport.user == undefined){
res.json({success: "false"});
} else{
regUser.findOneAndUpdate(
{ username:req.user.username },
{ $pull: { budgets : { uniqueId: parseFloat(req.param('id')) }} },
function(err, data){
if(err) return console.log(err);
res.json(data.budgets);
});
}
});

Resources