gpt4 book ai didi

javascript - Pubnub 函数 xhr 模块多次调用服务器端点(它应该只调用一次)

转载 作者:行者123 更新时间:2023-11-30 19:10:18 25 4
gpt4 key购买 nike

我一直在使用 pubnub 在移动设备之间进行实时通信。我正在创建的场景如下:

  1. 发件人移动设备将向 pubnub 发布消息。
  2. 消息将调用一个On Before Function PubNub Function where original消息被发送到它被持久化的 laravel 端点,并且数据库记录 ID 添加到消息中并发布给订阅者。

(使用 PN 函数中的 xhr 模块调用 Laravel 端点)

我面临的问题是,每次发布消息时,我的 Laravel 端点都会被调用大约 7 到 12 次。

下面是我的 onBefore PubNub 函数。

export default (request) => { 
console.log('intial message: ',request.message);
const kvstore = require('kvstore');
const xhr = require('xhr');
const http_options = {
"timeout": 5000, // 5 second timeout.
"method": "POST",
"body": "foo=bar&baz=faz"
};

const url = "redacted_backend_url";

return xhr.fetch(url,http_options).then((x) => {
console.log('Messages after calling ajax: ',request.message.content);
// here i am changing the message
request.message.content = 'hello world';
return request.ok();
}).catch(err=>console.log(err)) ;
}

请指出具体错误。

最佳答案

PubNub 函数通配符 channel 绑定(bind)

您的函数绑定(bind)到 channel '*' 这当然意味着捕获所有发布到所有 channel 。您不知道的是,函数中的 console.log 将消息发布到如下所示的 channel :blocks-output-kpElEbxa9VOgYMJQ.77042688368579w9

Functions 输出窗口订阅了该 channel 以显示您的 console.log。因此,当函数被调用时,它会向 console.log 的 channel 发布一条消息,该 channel 由您的函数捕获,调用 console.log 并最终配置递归达到限制以防止您陷入无限循环。

因此,如果您要将 channel 绑定(bind)更改为 foo.* 之类的内容并发布到 foo.bar 之类的 channel ,则可以避免这种不需​​要的递归。在生产中,console.logs 也应该被删除,它不会导致这种情况发生。

此外,您可以在您的函数顶部实现一些 channel 过滤条件,以防止它进一步执行您的函数代码:

if (channel.startsWith("blocks-output"))
return request.ok()
}

关于javascript - Pubnub 函数 xhr 模块多次调用服务器端点(它应该只调用一次),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58558723/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com