abc123
abc123

Reputation: 8303

In Loopback.js, how to respond to a remote method with an empty body if it has a return argument?

If I have a remote method like this:

Command.remoteMethod('invoke', {
  http: {verb: 'post', status: 200, source: 'body'},
  returns: {arg: "text", type: "string"}
});

Sometimes we need to respond with the text argument and sometimes with a completely empty body. In the remote method code, I have something like this:

Command.invoke = callback => {
  // ...

  if (error) {
    callback(null, 'There was an error');
  } else {
    callback(null);
  }
}

The problem is, in the else branch, the body is never empty. I've also tried: callback(null, null) and callback(null, '').

Is there a way to achieve this? Or do I need to implement a remote hook to manually modify the response to get what I'm after?

Upvotes: 1

Views: 777

Answers (2)

Nishant
Nishant

Reputation: 3704

Best way is to use the after remote function

if no content then you can add

ctx.res.statusCode = 204
ctx.res.end(null);

Upvotes: 2

Ebrahim Pasbani
Ebrahim Pasbani

Reputation: 9396

When you define a returns block in model.js, it means your remote method has a response body.

For your situation you can remove result in remote hooks.

Command.afterRemote("invoke", function(ctx, instance, next){
        //check if you want return text or nothing
        //if nothing so set result to null, otherwise just call next()
        ctx.result = null;
        next();
    });

Upvotes: 0

Related Questions