问题描述
我正在尝试将 Pusher 与 Wix HTTP 功能集成
例如:
向 Wix 站点发出 GET 请求(路径:'/findItems')。发出请求后,我想检查数据库中是否有新的项目插入。我发现,我可以用 afterInsert 钩子做到这一点。当钩子被钩住时,我想触发推送器。
这是我目前使用的代码 http-functions.js
:
import { ok,created,notFound,serverError } from 'wix-http-functions';
import wixData from 'wix-data';
import Pusher from "pusher";
const pusher = new Pusher({
appId: "xxxxx",key: "xxxxxxxxxxxxxxx",secret: "xxxxxxxxxxxx",cluster: "xxxx",useTLS: true
});
export function get_findItems(request) {
let options = {
"headers": {
"Content-Type": "application/json"
}
};
return wixData.query("users")
.eq("firstName",request.path[0])
.eq("lastName",request.path[1])
.find()
.then((results) => {
if (results.items.length > 0) {
options.body = {
"items": results.items
};
return ok(options);
}
options.body = {
"error": `'${request.path[0]} ${request.path[1]}' was not found`
};
return notFound(options);
})
.catch((error) => {
options.body = {
"error": error
};
return serverError(options);
});
}
export function post_newItem(request) {
let options = {
"headers": {
"Content-Type": "application/json"
}
};
return request.body.text()
.then( (body) => {
return wixData.insert("users",JSON.parse(body));
} )
.then( (results) => {
options.body = {
"inserted": results
};
return created(options);
} )
.catch( (error) => {
options.body = {
"error": error
};
return serverError(options);
} );
}
export function users_afterInsert(item,context) {
let hookContext = context;
pusher.trigger("channel","action",{
firstName: item.firstName,lastName: item.lastName
});
return item;
}
但不幸的是,Pusher 没有被触发。调试后,我发现 Pusher 包已安装并工作,但仅在 afterInsert 钩子中没有触发!
非常感谢任何帮助!
谢谢!
解决方法
afterInsert
钩子的代码需要在名为 data.js
的后端文件中,而不是在您现在拥有的 http-functions.js
文件中。