简体   繁体   English

保存后自定义环回响应

[英]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". 我有一个loopback 2.x应用程序,其中我有一个模型对话和模型消息,关系“对话有很多消息”。 I want to customize the response for POST conversations/:id/messages with a json response different than the default, say {status: 'success'} . 我想自定义POST conversations/:id/messages的响应,其json响应不同于默认值,比如{status: 'success'} I tried to use remote hook for the method __create__messages , but it did not work: 我试图使用远程钩子方法__create__messages ,但它不起作用:

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? 如何为远程方法返回自定义json? 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();
      });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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