Can't get sails-hook-validate to work with Sails v1.0? - sails.js

I am having an issue getting validation error messages to attach to the error object in sails v1.0. I am using the sails-hook-validate module.
User model:
module.exports = {
attributes: {
name: {
type: 'string',
required: true,
}
},
validationMessages: {
name: {
required: 'Name is required'
},
},
};
Running User.create in the sails console:
sails> User.create({}).exec(err => console.log(err.toJSON()));
{ error: 'E_UNKNOWN',
status: 500,
summary: 'Encountered an unexpected error',
Errors: undefined }
It appears sails-hook-validate is modifying the error object in some way, but it doesn't seem to be adding my custom error message in any way. Does anybody know how to get sails-hook-validate to work in Sails v1.0?

Sails v1 dramatically changed how validation errors are formatted and sails-hook-validate hasn't been updated to handle Sails v1 yet.

Sails-hook-validate is a third party hook and I dont think its been updated to work with Sails V1.
As #jeffery mentioned the structure of validation errors did change slightly in Sails V1 but there could be other changes that are effecting this hook.

Related

Getting "Invalid exit definition" on Compilation of Sails Helper (Sails v1.0)

I'm getting the error
Invalid exit definition ("success"). Must be a dictionary-- i.e. plain JavaScript object like `{}`.
Invalid exit definition ("error"). Must be a dictionary-- i.e. plain JavaScript object like `{}`.
when doing sails lift. The error is on getRole.js
module.exports = {
friendlyName: 'Get Role',
description: '',
inputs: {
user_id: {
friendlyName: 'User Id',
description: 'The ID of the user to check role',
type: 'string',
required: true
}
},
exits: {
success: function (role){
return role;
},
error: function (message) {
return message;
}
},
fn: function (inputs, exits) {
User.findOne({ id: inputs.user_id } , function (err, user) {
if (err) return exits.err(err);
return exits.success(user.role);
});
}
};
This is a new error, and looking at my git, nothing has changed in my code since it successfully compiled. I understand the Sails version (v1.0) I'm using in beta, so I'm taking that into account.
Exits cannot be defined as functions. There is a special syntax (Machine Spec) to define exits. In your example this should work:
exits: {
error: {
description: 'Unexpected error occurred.',
},
success: {
description: 'Role was succesffuly fetched'
}
},
You can read more info about helper exits here: https://next.sailsjs.com/documentation/concepts/helpers
May changes occur on the last release 1.0.0-38. I've not checked underneath yet, but the way to execute helpers changed: on .exec() I get errors. Now, use .switch();

how to sync data from ydn-db web app to backend server?

With ydn-dn, i want to automatically synchronise data from my web app with my REST back end.
I read the documentation and searched in examples but i cannot make it work.
https://yathit.github.io/ydn-db/synchronization.html
http://dev.yathit.com/api/ydn/db/schema.html#sync
I tried to define a schema with sync configuration like that :
var schema = {
stores: [ {
name: 'contact',
keyPath: 'id',
Sync: {
format: 'rest',
transport: service,
Options: {
baseUri: '/'
}
}
}
]
};
and created a function for transport :
var service = function(args) {
console.log("contact synch");
};
but my service function is never called.
I certainly misunderstood how YDN-db work, but i didn't found any example.
To complete, here is a jsfiddle :
http://jsfiddle.net/asicfr/y7sL7b3j/
Please see the example http://yathit.github.io/ydndb-demo/entity-sync/app.html
Older example http://yathit.github.io/sprintly-service/playground.html from https://github.com/yathit/sprintly-service

TDD of Sailsjs Waterline Models with Vowsjs

My problem is trying to do TDD of Waterline models. The tests I present are just boilerplate to get my suite constructed. Nevertheless, they raise valid issues. The primary problem is that I require the model in the Vows.js test. In the test scope the model is defined, but it does not have any properties inherited from the Waterline package. For example, here is some model code for "EducationLevel":
module.exports = {
migrate: 'safe',
tableName: 'education_levels',
attributes: {
id : { type: 'integer', required: true },
description: { type: 'string', required: true },
display_sort: { type: 'integer', required: true}
}
};
And here are some trial tests:
vows = require('vows')
assert = require('assert')
EducationLevel = require('../api/models/EducationLevel')
vows.describe('tac_models').addBatch({
'EducationLevel model' : {
topic: function(){
educationLevel = EducationLevel.create();
return true;
},
'It exists': function (topic) {
assert.equal(EducationLevel.create,undefined);
assert.equal(EducationLevel.migrate,undefined);
}
}
}).export(module)
When I run the test, the first assertion passed, but the second does not:
vows spec/*
✗
EducationLevel model
✗ It exists
» expected undefined,
got 'safe' (==) // tac_models.js:13
✗ Broken » 1 broken (1.545s)
This shows that the test knows only what is explicitly declared in the EducationLevel definition. The 'migrate' property is defined because I explicitly define it in the code. It does not know about the Waterline method 'create'. How can I remedy this in a way that makes conventional TDD practical?

How to implement ReST services with Sails.js?

I am quite new to Node. I came across Sails.js. I think it is based on WebSocket, which seems to be really good for building real-time applications. I would like to know that whether Sails can be used to implement REST architecture as it uses WebSocket? And if yes, how?
Yes it can. Sails JS allows you to easily build a RESTful API, essentially with no effort to get started. Also, websockets (through socket.io) are integrated by default into the view and api.
To create a fully RESTful app from the ground up, it actually requires no JS. Try:
sails new testapp
cd testapp
sails generate model user
sails generate controller user
cd <main root>
sails lift
The CRUD (Create, Read, Update, Delete) actions are already created for you. No code!
You can create a user in your browser by doing the following:
HTTP POST (using a tool like PostMan) to http://:1337/user/create
{
"firstName": "Bob",
"lastName": "Jones"
}
Next, do a GET to see the new user:
HTTP GET http://:1337/user/
FYI - Sails JS uses a default disk based database to get you going
Done.
sails new testapp
cd testapp
sails generate api apiName
controller
create: function (req, res) {
var payload = {
name:req.body.name,
price:req.body.price,
category:req.body.category,
author:req.body.author,
description:req.body.description
};
Book.create(payload).exec(function(err){
if(err){
res.status(500).json({'error':'something is not right'})
}else{
res.status(200).json({'success':true, 'result':payload, 'message':'Book Created success'})
}
});
},
readone: async function (req, res) {
var id = req.params.id;
var fff = await Book.find(id);
if(fff.length == 0){
res.status(500).json({'error':'No record found from this ID'})
}else{
res.status(200).json({'success':true, 'result':fff, 'message':'Record found'})
}
},
model
attributes: {
id: { type: 'number', autoIncrement: true },
name: { type: 'string', required: true, },
price: { type: 'number', required: true, },
category: { type: 'string', required: true, },
author: { type: 'string' },
description: { type: 'string' },
},
routes
'post /newbook': 'BookController.create',
'get /book/:id': 'BookController.readone',

Cannot save a document in Mongoose - Validator required failed for path error

Following is my schema:
var userSchema = new Schema({
username: {
type: String,
required: true
},
password: {
type: String,
required: false
}
});
Now, when I attempt to save a document of the above schema, I get the following error:
{ message: 'Validation failed',
name: 'ValidationError',
errors:
{ username:
{ message: 'Validator "required" failed for path username',
name: 'ValidatorError',
path: 'username',
type: 'required' } } }
The above is the error object returned by mongoose upon save. I searched for this error but could not understand what is wrong. The document that I am trying to save is as follows:
{
username: "foo"
password: "bar"
}
Any idea what this means? I searched the mongoose docs too but could not find anything under the validation section.
First, you are missing a comma (,) after foo.
Now, is { username: "foo", password: "bar" } JSON sent via http, our an actual object in your server-side code ?
If it is, try to console.log(youVariable.username) and see if it shows undefined or the value foo. If you see undefined, then your object is not parsed properly.
You can make sure that whom ever is sending the POST request is sending a "application/json" in the header, you could be receiving something else, thus your JSON isn't parsed to a valid javascript object.