Modifying ctx.result does not change POST response

732 views Asked by At

I'm modifying ctx.result on my model's after save operation hook to simplify the response of a POST method. The response should contain only the generated id and a response only property that is not part of the model:

MyModel.observe('after save', function(ctx, next) {
    if (ctx.instance && ctx.isNewInstance) {
        ctx.result = {
            id : ctx.instance.id,
            responseOnlyProperty: MyModel.getResponseOnlyPropertyValue()
        };
        console.log('result:', ctx.result);
    }
    next();
});

As expected ctx.result is written to the console with the new values set, but the response body sent back to the client still contains all model properties, and does not contain the newly added responseOnlyProperty.

What is the proper way to modify response body?

1

There are 1 answers

0
Alex V On BEST ANSWER

They suggest to use afterRemote hooks to adjust the response: how to modify the responses loopback sends. So, just move the logic you implemented into that method. Very likely, ctx.result is populated on the later stage and that's why whatever you put into ctx.result in the model hook, is overridden later.