1

假设我们有这样的模式:

type Subscription {
  objectAddedA: ObjectA
  objectAddedB: ObjectB
}

graphql 客户端可以同时订阅 objectAddedA 和 objectAddedB 订阅吗?我很难在网络上找到好的订阅示例,而且 graphql 文档似乎根本没有提到它们,除非我错过了它。我们正在设计一个在 kubernetes 中运行的系统,其中单个 pod 将获取 api 请求以添加/更新/删除配置,我们希望使用 graphql 订阅将这些更改推送到任何关心它们的 pod(它们将是 graphql 客户端)。然而,将会有许多不同的对象类型和潜在的几种不同类型的事件,他们希望随时得到通知,

4

1 回答 1

0

可以使用graphql-python/gql

请参阅此处的文档

提炼:

# First define all your queries using a session argument:

async def execute_query1(session):
    result = await session.execute(query1)
    print(result)

async def execute_query2(session):
    result = await session.execute(query2)
    print(result)

async def execute_subscription1(session):
    async for result in session.subscribe(subscription1):
        print(result)

async def execute_subscription2(session):
    async for result in session.subscribe(subscription2):
        print(result)

# Then create a couroutine which will connect to your API and run all your queries as tasks.
# We use a `backoff` decorator to reconnect using exponential backoff in case of connection failure.

@backoff.on_exception(backoff.expo, Exception, max_time=300)
async def graphql_connection():

    transport = WebsocketsTransport(url="wss://YOUR_URL")

    client = Client(transport=transport, fetch_schema_from_transport=True)

    async with client as session:
        task1 = asyncio.create_task(execute_query1(session))
        task2 = asyncio.create_task(execute_query2(session))
        task3 = asyncio.create_task(execute_subscription1(session))
        task4 = asyncio.create_task(execute_subscription2(session))

        await asyncio.gather(task1, task2, task3, task4)

asyncio.run(graphql_connection())
于 2021-12-15T16:58:57.960 回答