enguerran
enguerran

Reputation: 332

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);
  });
};

Upvotes: 7

Views: 6286

Answers (3)

asmmahmud
asmmahmud

Reputation: 5054

For loopback verion 2 and 3+: you can also use afterRemote hook to modify the response:

module.exports = function(MyModel) {  
  MyModel.afterRemote('create', function(
    context,
    remoteMethodOutput,
    next
  ) {
    context.res.statusCode = 201;
    next();
  });
};

This way, you don't have to modify or touch original method or its signature. You can also customize the output along with the status code from this hook.

Upvotes: 0

sojo2600
sojo2600

Reputation: 199

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},
    ...
  }
);

Upvotes: 3

Jake
Jake

Reputation: 7782

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.

Upvotes: 10

Related Questions