我在Apollo中遇到GraphQL订阅问题 . 我想订阅添加关于主题的“观点”(基本上添加了关于帖子的评论),我很确定我已正确设置服务器 . 客户端给我带来了麻烦 . (如果这个问题看起来很熟悉,我之前就问过它并且认为我得到了答案,但没有去) . 这是我的订阅架构:
type Subscription {
perspectiveAdded: Perspective
}
schema {
query: RootQuery
mutation: Mutation
subscription: Subscription
}
我的订阅解析器:
Subscription: {
perspectiveAdded(perspective) {
return perspective;
}
}
我的订阅管理员:
const pubsub = new PubSub();
const subscriptionManager = new SubscriptionManager({
schema,
pubsub,
setupFunctions: {
perspectiveAdded: (options, args) => {
perspectiveAdded: {
filter: (topic) => {
return topic
}
}
},
}
});
export { subscriptionManager, pubsub };
我的addPerspective变异的最后一部分是(订阅的事件触发器):
//...
return perspective.save((error, perspective) => {
if(error){
console.log(error);
}
//Publish it to Subscription channel
pubsub.publish('perspectiveAdded', perspective);
});
然后我连接了实际的服务器来支持订阅:
const PORT = process.env.PORT || 4000;
const server = createServer(app);
server.listen(PORT, ()=>{
new SubscriptionServer(
{
subscriptionManager: subscriptionManager,
onConnect: (connectionParams, webSocket) => {
console.log('Websocket connection established Lord Commander');
},
onSubscribe: (message, params, webSocket) => {
console.log("The client has been subscribed, Lord Commander", message, params);
},
onUnsubsribe: (webSocket) => {
console.log("Now unsubscribed, Lord Commander");
},
onDisconnect: (webSocket) => {
console.log('Now disconnected, Lord Commander');
}
},
{
server: server,
path: '/subscriptions',
});
console.log('Server is hot my Lord Commander!');
});
我也正确地连接了客户端,因为在我的终端中我看到了“ Build Websocket连接”消息 . 我难以理解的部分是如何实际调用订阅 . 根据Apollo博客,我应该能够在GraphiQL中测试订阅(因为我使用的是apollo服务器,现在是graphql-server-express),但它说“Resolve function for”Subscription.perspectiveAdded \“返回undefined ” .
对于我的组件,我试图连接'subscribeToMore'但是在浏览器控制台中,我收到一个错误对象,上面写着“从onSubscribe返回的无效参数!返回值必须是一个对象!”我不确定它指的是哪个对象 .
这是我的订阅查询,名为perspectiveSubscription:
export default gql`
subscription {
perspectiveAdded {
id
content
}
}
`;
和有线组件:
constructor(props){
super(props);
this.state = {};
this.subscription = null;
}
componentWillReceiveProps(nextProps) {
if (!this.subscription && !nextProps.data.loading) {
let { subscribeToMore } = this.props.data
this.subscription = subscribeToMore(
{
document: perspectiveSubscription,
updateQuery: (previousResult, { subscriptionData }) => {
if(!subscriptionData.data){
console.log('no new subscription data');
return previousResult;
}
const newPerspective = subscriptionData.data.perspectiveAdded;
console.log(newPerspective);
return Object.assign({}, previousResult, newPerspective);
}
}
)
}
从这里,我在终端中收到一条消息,说客户端已经订阅,但我仍然得到上面提到的错误对象 . 我已经把头发拉了几天 - 你们有没有看到我在这里缺少的东西?具体来说,客户端的任何想法?感谢大家!
1 回答
看起来服务器端不正确,因为添加了订阅并且graphiql也没有提供正确的结果 .
我建议的一件事是你检查 Channels 定义:
并且还检查是否在pubsub调用之前保存并定义了透视对象 . 而且我认为您还想添加一个评论ID,订阅应该正常工作 . 在我这边看起来或多或少像在这个post