Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change http status codes in Strongloop Loopback

I am trying to modify the http status code of create.

POST /api/users
{
    "lastname": "wqe",
    "firstname": "qwe",
}

Returns 200 instead of 201

I can do something like that for errors:

var err = new Error();
err.statusCode = 406;
return callback(err, info);

But I can't find how to change status code for create.

I found the create method:

MySQL.prototype.create = function (model, data, callback) {
  var fields = this.toFields(model, data);
  var sql = 'INSERT INTO ' + this.tableEscaped(model);
  if (fields) {
    sql += ' SET ' + fields;
  } else {
    sql += ' VALUES ()';
  }
  this.query(sql, function (err, info) {
    callback(err, info && info.insertId);
  });
};
like image 786
enguerran Avatar asked Nov 14 '14 15:11

enguerran


2 Answers

In your call to remoteMethod you can add a function to the response directly. This is accomplished with the rest.after option:

function responseStatus(status) {
  return function(context, callback) {
    var result = context.result;
    if(testResult(result)) { // testResult is some method for checking that you have the correct return data
      context.res.statusCode = status;
    }
    return callback();
  }
}

MyModel.remoteMethod('create', {
  description: 'Create a new object and persist it into the data source',
  accepts: {arg: 'data', type: 'object', description: 'Model instance data', http: {source: 'body'}},
  returns: {arg: 'data', type: mname, root: true},
  http: {verb: 'post', path: '/'},
  rest: {after: responseStatus(201) }
});

Note: It appears that strongloop will force a 204 "No Content" if the context.result value is falsey. To get around this I simply pass back an empty object {} with my desired status code.

like image 154
Jake Avatar answered Oct 23 '22 18:10

Jake


You can specify a default success response code for a remote method in the http parameter.

MyModel.remoteMethod(
  'create',
  {
    http: {path: '/', verb: 'post', status: 201},
    ...
  }
);
like image 39
sojo2600 Avatar answered Oct 23 '22 17:10

sojo2600