Subscriptions

Relay 公开以下API以创建 subscriptions.

const {requestSubscription} = require('react-relay');

type Variables = {[name: string]: any};

requestSubscription(
  environment: Environment,
  config: {
    subscription: GraphQLTaggedNode,
    variables: Variables,
    onCompleted?: ?() => void,
    onError?: ?(error: Error) => void,
    onNext?: ?(response: ?Object) => void,
    updater?: ?(store: RecordSourceSelectorProxy, data: SelectorData) => void,
    configs?: Array<RelayMutationConfig>,
  },
);

现在我们来看一下 config:

  • subscription: graphql 标记的 subscription 查询.
  • variables: 包含 subscription 所需变量的对象。
  • onCompleted: 当 subscription 被 没有错误地关闭,执行回调函数。
  • onError: 当Relay或服务器遇到处理subscription 的错误时,执行回调函数。
  • onNext: 每次从服务器接收到响应时执行回调函数,并使用原始的GraphQL响应有效负载。
  • updater: 可选功能,可根据服务器响应提供更新内存 Relay 存储的自定义逻辑。
  • configs: 包含更新器配置的数组。在commitMutation中这是一样的作为 配置

示例 #

在一个简单的 subscription, y你只需要 subscriptionvariables。 当您只更改现有记录的属性时,这是合适的 id:

const {
  requestSubscription,
  graphql,
} = require('react-relay');

const subscription = graphql`
  subscription MarkReadNotificationSubscription(
    $storyID: ID!
  ) {
    markReadNotification(storyID: $storyID) {
      notification {
        seenState
      }
    }
  }
`;

const variables = {
  storyID,
};

requestSubscription(
  yourEnvironment, // see Environment docs
  {
    subscription,
    variables,
    // optional but recommended:
    onCompleted: () => {/* server closed the subscription */},
    onError: error => console.error(error),
  }
);

每次响应更新客户端 #

对于更复杂的用例,您可能希望在收到每个 时执行自定义逻辑来更新 Relay 缓存。要这样做,传递一个 updater 函数:

const {ConnectionHandler} = require('relay-runtime');

requestSubscription(
  environment,
  {
    subscription,
    variables,
    updater: store => {
      // Get the notification
      const rootField = store.getRootField('markReadNotification');
      const notification = rootField.getLinkedRecord('notification');
      // Add it to a connection
      const viewer = store.getRoot().getLinkedRecord('viewer');
      const notifications =
        ConnectionHandler.getConnection(viewer, 'notifications');
      const edge = ConnectionHandler.createEdge(
        store,
        notifications,
        notification,
        '<TypeOfNotificationsEdge>',
      );
      ConnectionHandler.insertEdgeAfter(notifications, edge);
    },
  },
);