@aaronpowell/graphql-cosmosdb-subscriptions 中文文档教程

发布于 4年前 浏览 20 项目主页 更新于 3年前

CosmosDB GraphQL Subscriptions npm - CosmosDB package

此软件包包含对 Apollo GraphQL 订阅 的支持,使用 Azure CosmosDB 更改源

Installation

通过 npm 或 GitHub Packages 安装:

$> npm install --save @aaronpowell/graphql-cosmosdb-subscriptions

Usage

您需要一个 SignalR 服务帐户(如果您没有 Azure 帐户 免费注册)。 复制连接字符串并在您创建 SignalRPubSub 实例时提供它:

import { CosmosDBPubSub } from "@aaronpowell/graphql-cosmosdb-subscriptions";

const cosmosPubSub = new CosmosDBPubSub(
  new CosmosClient(process.env.COSMOS_CONNECTION_STRING || "")
    .database(process.env.COSMOS_DB || "")
    .container(process.env.COSMOS_CONTAINER || "")
);

与大多数 pubsub 库不同,您不需要直接发布,当 Change Feed 收到消息时就会收到消息。 创建订阅时,您订阅了一个 CosmosDB 分区键值(在下面的示例中,type 是分区键,我们在 type = 'message' 时订阅)。

export const resolvers = {
  Query: {
    async hello(parent, args, { dataSources }) {
      const text = `Message! ${Date.now()}`;
      await dataSources.messages.createOne({
        id: Date.now() + "",
        text,
        type: "message",
      });
      return text;
    },
  },
  Subscription: {
    getMessage: {
      subscribe: () => cosmosPubSub.asyncIterator(["message"]),
    },
  },
};

CosmosDB GraphQL Subscriptions npm - CosmosDB package

This package contains support for Apollo GraphQL Subscriptions, using the Azure CosmosDB Change Feed.

Installation

Install via npm or GitHub Packages:

$> npm install --save @aaronpowell/graphql-cosmosdb-subscriptions

Usage

You'll need a SignalR Service account (if you don't have an Azure account sign up for free). Copy the connection string and provide it when you create an instance of SignalRPubSub:

import { CosmosDBPubSub } from "@aaronpowell/graphql-cosmosdb-subscriptions";

const cosmosPubSub = new CosmosDBPubSub(
  new CosmosClient(process.env.COSMOS_CONNECTION_STRING || "")
    .database(process.env.COSMOS_DB || "")
    .container(process.env.COSMOS_CONTAINER || "")
);

Unlike most pubsub libraries, you don't need to publish directly, messages are received when the Change Feed receives messages. When creating the subscription, you subscribe to a CosmosDB partition key value (in the below example type is the partition key and we're subscription when type = 'message').

export const resolvers = {
  Query: {
    async hello(parent, args, { dataSources }) {
      const text = `Message! ${Date.now()}`;
      await dataSources.messages.createOne({
        id: Date.now() + "",
        text,
        type: "message",
      });
      return text;
    },
  },
  Subscription: {
    getMessage: {
      subscribe: () => cosmosPubSub.asyncIterator(["message"]),
    },
  },
};
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文