简体   繁体   中英

Customize Loopback response after save

I have a loopback 2.x app, in which I have a model Conversation and a model Message, with a relationship "Conversation has many messages". I want to customize the response for POST conversations/:id/messages with a json response different than the default, say {status: 'success'} . I tried to use remote hook for the method __create__messages , but it did not work:

Conversation.afterRemote('__create__messages', function(ctx, next) {
  ctx.result.data = {
    success: 'yes'
  };
  next();
});

This still returns the default response. How can I return a custom json for a remote method? I have seen examples only for all models, or for all methods: multiple models , multiple methods

Maybe you can try a version of following code below. Also, I think you are meaning to to manipulate data before the method finishes, not after. If you wait, the response will already be created, preventing your intended goal. Let me know if this works (replace with methods that will work for your use case).

   Conversation.observe('before save', function(context, next) {
        var instance = context.instance || context.data;
        if (!instance) return next();
        // Your code here
        next();
      });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM