I was wondering what happens in Sails when you pass information in through the URL. For example, if you were to type:
localhost:1337/project/create?Id=2&Name=John
how does Sails create that into a model? I need to be able to take the name and pass it to separate database, but I have no idea how to access the information (such as name=John, in this case) after each creation.
Thanks, I appreciate it!
Under your api/models/project.js file you can override afterCreate method like doc say :
afterCreate: fn(newlyInsertedRecord, cb)
More here : http://sailsjs.org/#!/documentation/concepts/ORM/Lifecyclecallbacks.html
Related
Subject says it all really. Just trying to figure out how to expose the verficationToken property of the default built-in user model in Loopback 3.
I've tried adding it to the "scope" definition in users.json, it works for other fields but not for verificationToken. I've also made sure to remove it from the "hidden" array in users.json.
I've read the very limited information provided on white-listing here (https://loopback.io/doc/en/lb3/Model-definition-JSON-file.html) and it talks about overwriting the toJSON method of the model, but I'm not seeing much info on how to do that, particularly for a built-in model.
Anybody every dealt with this before? Thanks in advance for any tips you might provide!
To access verification token,If you are using User.json by default it hides the password and verificationToken from accessing in rest api
By Default
"hidden": ["password", "verificationToken"],
change it to
"hidden": ["password"],
With the find and update methods i am able to restrict fetching of data restricted to the logged in user by adding a policy that sets req.options.where.owner = userID, therefore i dont need to create custom controllers or models for these methods.
With update and create i can also set req.options.values.owner = userID so that the user cant create or update an object that will belong to another user.
But the problem is that the blueprint findOne controller does not have any options for this kind of filtering, so any logged in user can request an object created and owned by another user.
Is there anyway i can restrict findOne without writing my own controller and query?
Found a solution to the problem, what you can do is to override the default blueprint action by creating a folder named blueprints in your api folder, there you can create a findone.js (lowercase) file,
copy the original blueprint action from /node_modules/sails/lib/hooks/blueprints/actions/findOne.js to /api/blueprints/findone.js
add .where( actionUtil.parseCriteria(req) ); to the query.
Dont forget to change the path of actionutil from require('../actionUtil'); to require('../../node_modules/sails/lib/hooks/blueprints/actionUtil');
Voila, now the findOne action will respect your req.options.where queries.
You can specify blueprint in your policies like this
module.exports = function (req, res, next) {
var blueprint = req.options.action;
if (blueprint === 'findOne') {
// do restriction here
return next();
}
res.forbidden('not allowed to do something');
};
I'm rather forget, is blueprint name findOne or findone.
I need to extend res.json so that the response goes out as text with a csrf token eg
&&&CSRF&&&{foo:bar}
Sails seems to use a different csrf methodology, but I need to do it this way to match the preexisting client side codebase.
Ideally I need to be able to create a new function:
return res.jsonWithCsrf({
foo: bar
});
Internally this would call res.json but would wrap the csfr token around the response.
I gather that I need to write a hook but am unsure how to do it.
You can create custom responses by placing your file in the api/responses directory.
You can see the files that are already there, modify them if you want, or create your own.
If you were to create jsonWithCsrf.js in that folder, then you can access it in the manner you describe above.
res.jsonWithCsrf()
http://sailsjs.org/#!/documentation/concepts/Custom-Responses
Im working on ember-cli, how do i change rest call on fly in the rest adapter. If i use path params not query params?for example:
export default DS.RESTAdapter.extend({
namespace:'res/v1/users/id',
pathForType: function() {
return Ember.String.underscore("friends");},});
Based on the user selection from dropdown we get the "id", using the id I need to get user friends from the database.
Could you please suggest a better way to do. My aapplication supports pathparams not the query params
To customize the URL, override the buildURL method in your adapter.
The tricky part is to access related records from the adapter. For example, you request friends for a given user. You work in a friend adapter, but you need to know the user's id to include it in the URL.
For that purpose, use the record property on the snapshot argument of the buildURL method.
Alternatively, you might want to override some of buildURL's underlying methods such as urlForFindQuery, depending on how you request your model from the store. With a find.query(), you will retrieve the id of the user from the query.
If this does not help you, please respond with the way you're trying to fetch friends from the store.
I have created a variable in enviroment.js 'userId'. When ever i select a user
i set config.userId in the controller to the corresponding Id.
config.userId=this.get('selectedUser');
In pathforType of adapter I used this varible
pathForType: function() {
return Ember.String.underscore(config.userId+"/friends");
}
you just need to add an import statement
import config from '../config/environment';
Please suggest me if anyone get to know better way. Thanks all for your responses
buildURL() only takes the type imo. so you have to pass some more jazz.
i did something along the lines of the following in the application adapter
$ ember generate adapter application
app/adapters/application.js
import DS from 'ember-data';
export default DS.RESTAdapter.extend({
findQuery: function(store, type, query) {
var urlQuery = query.theshityouwant;
var reply = this.ajax(this.buildURL(type.typeKey + '/' + urlQuery), 'GET', { headers: all});
return reply;
},
})
});
I have a few questions that I couldn't find answers anywhere online.
Does sails.js framework support HTTP PATCH method? If not - does anyone know if there is a planned feature in the future?
By default if I create method in a controller it is accessible with GET request is it the routes.js file where I need to specify that method is accessible only via POST or other type of methods?
How would you create a policy that would allow to change protected fields on entity only for specific rights having users. I.e: user that created entity can change "name", "description" fields but would not be able to change "comments" array unless user is ADMIN?
How would you add a custom header to "find" method which specifies how many items there are in database? I.e.: I have /api/posts/ and I do query for finding specific items {skip: 20; limit: 20} I would like to get response with those items and total count of items that would match query without SKIP and LIMIT modifiers. One thing that comes to my mind is that a policy that adds that that custom header would be a good choice but maybe there is a better one.
Is there any way to write a middle-ware that would be executed just before sending response to the client. I.e.: I just want to filter output JSON not to containt some values or add my own without touching the controller method.
Thank you in advance
I can help with 2 and 5. In my own experience, here is what I have done:
2) I usually just check req.method in the controller. If it's not a method I want to support, I respond with a 404 page. For example:
module.exports = {
myAction: function(req, res){
if (req.method != 'POST')
return res.notFound();
// Desired controller action logic here
}
}
5) I create services in api/services when I want to do this. You define functions in a service that accept callbacks as arguments so that you can then send your response from the controller after the service function finishes executing. You can access any service by the name of the file. For example, if I had MyService.js in api/services, and I needed it to work with the request body, I would add a function to it like this:
exports.myServiceFunction = function(requestBody, callback){
// Work with the request body and data access here to create
// data to give back to the controller
callback(data);
};
Then, I can use this service from the controller like so:
module.exports = {
myAction: function(req, res){
MyService.myServiceFunction(req.body, function(data){
res.json(data);
});
}
}
In your case, the data that the service sends back to the controller through the callback would be the filtered JSON.
I'm sorry I can't answer your other questions, but I hope this helps a bit. I'm still new to Sails.js and am constantly learning new things, so others might have better suggestions. Still, I hope I have answered two of your questions.