gpt4 book ai didi

graphql - 嵌套在类型中的 Apollo 服务器订阅

转载 作者:行者123 更新时间:2023-12-02 03:04:50 26 4
gpt4 key购买 nike

我正在尝试获取在 Apollo Server 2 中工作的订阅的解析器。当订阅是顶级字段时(即直接在 Subscription 根目录下的 schema 下),订阅才能工作。

但是,如果订阅包含在另一个 type 中,我总是收到错误 Subscription field must return Async Iterable. Received: undefined在客户端的 websocket 连接上——服务器的解析器永远不会被执行。

即这个模式有效:

type Subscription {
postAdded: Post
}

但是这个没有:

type Subscription {
post: PostSubscription
}

type PostSubscription {
postAdded: Post
}

我的第二种情况的解析器看起来像这样,但我尝试了很多不同的变体,但没有成功:

Subscription: {
post: () => ({
PostSubscription: {}
})
},
PostSubscription: {
postAdded: {
subscribe: () => pubSub.asyncIterator(['postAdded'])
}
}

最佳答案

错误消息表示您的帖子解析器


Subscription: {
post: () => ({
PostSubscription: {} // This needs to return AsyncIterator
})
},

如果我理解正确的话,你想订阅 postAdded、postDeleted、postUpdated,这三个帖子都在帖子下。我知道您想尝试在同一模型下对它们进行命名,这有助于更好地组织。但它有一些问题,我稍后会解释它们。

一句话建议: 最好将这 3 个字段直接放在根订阅字段下。

并不是说你做不到,而是如果你真的想做,假设您正在订阅


Subscription{
post{
postAdded: Post
postDeleted: Post
postUpdated(id:Int!): Post
}
}

那么这三个嵌套字段都“共享”同一个 channel 。

然后您需要做几件事

  1. post 的订阅函数返回异步迭代器,不是 postAdd,而是 post 字段。

Subscription: {
post: {
subscription: () => pubSub.asyncIterator(['postChannel'])
}
}

  • 然后在突变函数中,后突变(添加、更新、删除),您将需要弄清楚要发送给客户端的内容。
  • 类似这样的事情


    Mutation{
    createPost: (_,args,context,info)=>{
    const createdObject = // do create
    pubsub.publish("postChannel", {
    post:{
    // do not do postUpdate, postDelete, because there's nothing updated, deleted
    postAdded:createdObject
    }
    })
    }
    }

    这将使您想要的东西发挥作用,但这有几个问题。1. 每当发生任何更新/创建/删除时,都会通知客户端。这可能会给客户提供不正确的信息。像这样如果客户订阅

    subscription{
    post{
    postAdded
    }
    }

    然后,当其他人更新帖子时,客户将收到这样的回复

    response = {
    subscription:{
    postAdded:null
    }
    }

    忽略 postAdd 的 null 可能是可以的。但这对于postUpdate来说肯定是一个问题。想象一下用户订阅了

    subscribe{
    post{
    postUpdate(id:1)
    }
    }

    然后有人添加了帖子,客户端总是会收到通知,因为这三个事件共享同一个 channel 。然后他会收到

    response = {
    subscription:{
    postUpdated:null
    }
    }

    然后,如果你使用apollo客户端,它会从缓存中删除post:1,因为它会认为post为null。

    由于这些问题,强烈建议创建多个 channel ,最好每个模型创建三个 channel 。并创建三个根级订阅而不是嵌套它们。

    对于最低工作订阅,我会将您重定向到我为演示订阅而制作的 git-repo https://github.com/hansololai/apollo_subscription_boilerplate

    关于graphql - 嵌套在类型中的 Apollo 服务器订阅,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51862571/

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