How to change http status codes in Loopback Strongloop

I am trying to change the http status code to create.

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

Returns 200 instead of 201

I can do something similar for errors:

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

But I can not find how to change the status code to 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); }); }; 
+5
source share
2 answers

When calling remoteMethod you can add a function to the response directly. This is done using 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 looks like strongloop will cause 204 "No content" if the value of context.result false. To get around this, I just pass an empty {} object with my desired status code.

+8
source

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

 MyModel.remoteMethod( 'create', { http: {path: '/', verb: 'post', status: 201}, ... } ); 
+1
source

Source: https://habr.com/ru/post/1206884/


All Articles