Gary
Gary

Reputation: 395

Sails - Access Controller function(req,res) from Service

I have a Controller method: DbController.create to create database entries. This is the following format:

create: function (req, res) {
    var params = req.body;
    Db.create({
...

There is a route for this Controller method:

 'POST /createData': 'DbController.create'

I can use CURL to this URL with no problems (curl -X POST --data 'userId="testuser1"' http://localhost:1337/createData), and from my UI code I can call this using sails-io.js and io.socket.post(....).

The problem is that I want to use this from my Service now (DbService). I'm not sure how I can go about this, because simply using DbController.create requires a req and res parameter to be passed, but all I have is the data/params/body. Thanks

Upvotes: 0

Views: 69

Answers (1)

khushalbokadey
khushalbokadey

Reputation: 1152

The best way would be to move the create logic in some service method so that it can be used from anywhere in project. Once this is done, then invoke that method with necessary parameters from DbController.create as well as from some other service.

Sample:

// DBService:

createData: (params, callback) => {
    Db.create(params)...
}

// DBController:

create: (req, res) => {
    const params = req.body;
    DBService.createData(params, (err, results) => {
        if (err) {
            return res.serverError(err);
        }
        return res.json(results);
    });
}

// SomeOtherService:

someMethod: (params, callback) => {
    DBService.createData(params, callback);
}

Another way (which will unnecessary make http request) is to make a HTTP call from service to the API endpoint of DbController.create from the service.

Upvotes: 2

Related Questions