myusuf
myusuf

Reputation: 12240

Sailsjs: Setting response method based on request parameter

So I have been working on a SPA project using Sailsjs. The problem is:

When the first page loads, I use res.view or res.render in my controller. But, for subsequent requests, I dont want to use res.view or res.render, rather I'd like to use res.json.

Right now, I use the method:

return req.param('json') ? res.json(myObj) : res.view('layout', myObj);

This works, but I was looking for a more generic and abstract method in which my controller itself would know (on the basis of req.param('json')) whether to use res.view or res.json without me having to tell it explicitly.

Any help ?

Upvotes: 0

Views: 1017

Answers (2)

sgress454
sgress454

Reputation: 24948

This is what res.ok() is for.

In the controller action below, res.ok will either display the myAction.ejs using data as the view locals, or respond with data as JSON, depending on how the request came in (i.e. via AJAX, sockets or a regular browser request):

module.exports = {

    myAction: function(req, res) {

       var data = {someKey: "someVal"};

       return res.ok(data);

    }

}

Internally, the ok response uses req.wantsJSON to determine what to do; it checks headers, looks for an xhr object and generally does its best to guess your intent. req.wantsJSON is available for all requests (as is req.isSocket), so you can use them yourself as needed.

Upvotes: 2

myusuf
myusuf

Reputation: 12240

So after a bit of tinkering, I resolved this using a service.

I wrote a service (in GlobalUtils.js):

render: function (req, res, obj) {
    if(req.param('json')) {
        return res.json(obj);
    }
    else {
        return res.view('layout', obj);
    }
}

And I use this service in my controllers, like so:

return GlobalUtils.render(req, res, myObj);

But still, looking for a better method.

Upvotes: 0

Related Questions