Sails.js handling attribute validation errors - javascript

In Sails.js it is possible to use different database connections for models and it is easy to change database (MySQL or MongoDB). The problem arises when I want to display validation errors. These are my codes:
Groups.js model
...
connection: 'MysqlConnection', //or connection: 'MongodbConnection'
attributes: {
id: {
type: 'string',
unique: true
},
name: {
type: 'string',
required: true
},
...
GroupsController.js controller:
...
//add group to database
Groups.create(group, function (err, data) {
if (err) {
console.log(err);
res.send('Error'); // is it possible to send only validation error
return;
} else {
res.send(data);
}
});
...
Should I handle each attribute validation error separately, is it possible to send only validation error?
MySQL returns:
Error (E_VALIDATION) :: 1 attribute is invalid ...
MongoDB returns:
Error (E_UNKNOWN) :: Encountered an unexpected error ...

you can try:
Model.catch(function(err) {
var inspect = Object.keys(err)// [ "reason","invalidAttributes", ".." ]
console.log( Object.keys(err.invalidAttributes) ) // ["name","etc.."]
})
to catch the error

Related

Show NodeJS Errors in main html file itself

I made a form using NodeJs, i made some validations of input that show errors when user enter wrong values, the problem here is that the error appear on a new blank page but i need the error to appear on the main html file itself with cool styling
here's the live site http://mido.sundays.org.uk
I tried to make post request on the same route to see if the error will appear on the same page or not but the page turned to white blank page with the text inside
app.post('/', function (req, res) {
const SchemaValidation = {
name: joi.string().min(4).required().error(() => {
return {
message: 'Name is required. (min:4 chars)',
};
}),
email: joi.string().email().error(() => {
return {
message: 'Email field can\'t be Empty',
};
}),
phone: joi.string().min(8).max(14).required().error(() => {
return {
message: 'Valid Phone number is Required (min:8 characters - max: 14 characters)',
};
}),
university: joi.string().required().error(() => {
return {
message: 'University Field is Required',
};
}),
faculty: joi.string().required().error(() => {
return {
message: 'Faculty Field is Required',
};
}),
academicyear: joi.string().required().error(() => {
return {
message: 'Academic Year Field is Required and should range from 1-6',
};
}),
workshop: joi.array()
.items(joi.string().error(() => {
return {
message: 'You Should pickup 2 Committees',
};
})),
first_choice: joi.string().required().error(() => {
return {
message: 'You should pickup first choice',
};
}),
second_choice: joi.string().required().error(() => {
return {
message: 'You should pickup second choice',
};
}),
};
joi.validate(req.body,SchemaValidation,(err, result) => {
if(err) {
res.send(`<p style='color:red; text-align:center; margin-top:20px;'>${err.details[0].message}</p>`);
return; // don't try saving to db if the schema isnt valid
}
else
res.send(`<p style='color:green; text-align:center; margin-top:20px;'>Successfully Posted Data</p>`);
})
});
All what i need is to show the error in the same page and prevent the submit..
To solve this problem, I highly racommand you to use Pug.js (Template Engine), because you can't pass parameters into a specific page. By using a template engine, you can pass data as object, and render them with res.render('index', {error: res.error.message}).
You will be able to output into the page from server side the error object displaying whatever you needed to display!
res.send('content') basically it's a document.write()
https://pugjs.org/api/getting-started.html
Is there a reason you can't do the validation on the front end before submitting the form? That is usually the preferred way. You can have some backend validation so that you don't get bad data into your db but once you send a request you need to send a response back and in your case the response is the message not the entire HTML page. You can create a validation by adding an event listener to your submit button then using Ajax once you validate to send the data to the backend or you can use Bootstrap's built in validation and not mess with Ajax just through the form action. https://getbootstrap.com/docs/4.0/components/forms/#validation

Meanjs Forbidden Error

I am a new bee in AngularJs,below is the policy code created by Meanjs yo generator ,for learning purpose have created a library management system ,The problem what i am facing is when i am testing my server code i.e the API through browser URL...I am getting the result for
http://localhost:3000/api/searchbooks/bookname/davincicode as JSON Object
but for below url it's giving me {message: 'User is not authorized'}
http://localhost:3000/api/searchbooks/bookname/davincicode/bookName
exports.invokeRolesPolicies = function () {
acl.allow([
{
roles: ['user'],
allows: [{
resources: '/api/searchbooks',
permissions: ['get']
}, {
resources: '/api/searchbooks/bookname/:searchbookName',
permissions: ['get']
}]
},
{
roles: ['user'],
allows: [{
resources: '/api/searchbooks/bookname',
permissions: ['get']
}, {
resources: '/api/searchbooks/bookname/:searchbookName/:action',
permissions: ['get']
}]
}
])};
exports.isAllowed = function (req, res, next) {
var roles = (req.user) ? req.user.roles : ['guest'];
// If an Searchbook is being processed and the current user created it then allow any manipulation
if (req.searchbook && req.user && req.searchbook.user && req.searchbook.user.id === req.user.id) {
return next();
}
// Check for user roles
acl.areAnyRolesAllowed(roles, req.route.path, req.method.toLowerCase(), function (err, isAllowed) {
if (err) {
// An authorization error occurred
return res.status(500).send('Unexpected authorization error');
} else {
if (isAllowed) {
// Access granted! Invoke next middleware
return next();
} else {
return res.status(403).json({
message: 'User is not authorized'
});
}
}
});
};
I checked my role it's going as user only ,unable to find so specific question elsewhere pls help or provide some pointers.
I have got the issue made mistake in routing part :
app.route('/api/searchbooks/bookname/:searchbookName/:actionValue').all(searchbooksPolicy.isAllowed)
.get(searchbooks.read)
Here in policy url its action and i have to give actionValue as the parameter name.
so passing incorrect parameter name was an issue..

InvalidInput: Invalid request on AWS Route 53

I am trying to set resource records in AWS route 53 via the SDK and I am getting an Invalid Request error(InvalidInput). Can you double check my params to make sure that I have them set correctly?
function testw () {
var params = {
ChangeBatch: {
Changes: [
{
Action: 'CREATE',
ResourceRecordSet: {
Name: 'example.com',
Type: 'A',
AliasTarget: {
DNSName: 's3-website-us-east-1.amazonaws.com',
EvaluateTargetHealth: false,
HostedZoneId: 'Z1YU6G6WEXAMP'
},
}
},
],
Comment: 'This is a test and it should be working.'
},
HostedZoneId: 'Z1YU6G6WEXAMP'
};
route53.changeResourceRecordSets(params, function (err, data) {
if (err) console.log(err, err.stack); // an error occurred
else console.log(data); // successful response
});
}
Thanks for any help!!
Can you try removing the TTL? When you use aliases, you do not specify the TTL as Route 53 will use the target's TTL. Also, per the documentation, your alias target zone id should be Z3AQBSTGFYJSTF.

Ember data: Rollback createRecord on error

I'm trying to find the best way to avoid adding a record when there's an error using Ember Data:
This is my code:
createUser: function() {
// Create the new User model
var user = this.store.createRecord('user', {
firstName: this.get('firstName'),
lastName: this.get('lastName'),
email: this.get('email')
});
user.save().then(function() {
console.log("User saved.");
}, function(response) {
console.log("Error.");
});
},
I'm validating the schema on backend and returning a 422 Error in case it fails.
If I don't handle the error, the record is added to the site and I also get a console error.
So I did this:
user.save().then(function() {
console.log("User saved.");
}, function(response) {
user.destroyRecord();
});
Which kind of works deleting the record after reading the server response but:
1) I see the record appearing and dissapearing (like a visual glitch to say it somehow).
2) The console error still appears.
Is there a way to better handle this? I mean, is there a way to avoid adding the record when the server returns an error? Is there a way to avoid showing the console error?
Thanks in advance
You'll need to catch the error in the controller and then use deleteRecord() to remove it from the store:
actions: {
createContent() {
let record = this.store.createRecord('post', {
title: ''
});
record.save()
.then(rec => {
// do stuff on success
})
.catch(err => {
record.deleteRecord();
// do other stuff on error
});
}
}

Inserting an event with the nodejs google calendar API returns 400: "Missing end time"

I am trying to insert events via the Google Calendar API with a service account. The goal is to have one calendar that all users view: a server-to-server setup.
As of now, I can properly call the calendar API and list the events on said calendar:
var moment = require("moment"),
googleapis = require("googleapis"),
googleCal = googleapis.calendar("v3");
serviceEmail = "********#developer.gserviceaccount.com",
serviceKeyFile = "./key.pem";
var authClient = new googleapis.auth.JWT(
serviceEmail,
serviceKeyFile,
null,
["https://www.googleapis.com/auth/calendar"]
);
authClient.authorize(function (err, tokens) {
if (err) {
console.log(err);
} else {
googleCal.events.list({
auth: authClient,
calendarId: "********#gmail.com",
fields: {
items: ["end","start","summary"]
}
}, function (err, CL) {
if (err) {
console.log(err);
} else {
console.log(CL);
}
});
}
})
This properly returns a JSON object that lists all the different objects on the calendar. However, when I try to insert an event directly below the googleCal.events.list call:
googleCal.events.insert({
auth: authClient,
calendarId: "primary",
resources: {
start: {
dateTime: "2014-07-23T18:25:00.000-07:00",
timeZone: "America/New_York"
},
end: {
dateTime: "2014-07-23T19:25:00.000-07:00",
timeZone: "America/New_York"
},
summary: "winning # life",
description: "winning # life description"
}
}, function (err, something) {
if (err) {
console.log(err);
} else {
console.log(something);
// do something else
}
})
The following 400 is returned:
{ errors:
[ { domain: 'global',
reason: 'required',
message: 'Missing end time.' } ],
code: 400,
message: 'Missing end time.'}
How do I go about fixing this? The authorization is clearly working—I know because I've used up my unauthorized requests for the day and because I can list all the events. I have also specified an endTime. Why is the google calendar API telling me that I haven't?
I think the problem is in the keyword "resources" on line 4 of your second snippet. Based on the documentation, it should be a "resource":
* #param {object} params.resource - Request body data

Categories

Resources