How to change http status codes in Strongloop Loopback
Asked Answered
A

3

7

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);
  });
};
Aramaic answered 14/11, 2014 at 15:7 Comment(1)
I have been trying to figure this out as well. More comprehensive documentation would be nice :(Dismount
D
10

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.

Dismount answered 15/11, 2014 at 4:9 Comment(0)
S
3

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},
    ...
  }
);
Sonorant answered 17/3, 2016 at 19:21 Comment(0)
R
0

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.

Riti answered 25/4, 2018 at 3:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.