浅谈graphql的订阅模式

2,849 阅读2分钟

唠叨几句

这几天一直在看 Graphql结合Apollo的官网和资料,加上最近遇到的一些问题所以整理一下最近写的GraphqlApollo订阅模式

1.配置Apollo文件需要的依赖

import { getMainDefinition } from 'apollo-utilities'
import { split } from 'apollo-link'
import { createHttpLink } from 'apollo-link-http'
import { WebSocketLink } from 'apollo-link-ws';

1.5首先需要使用WebSocketLink来进行订阅链接

const makeApolloClient = (token = `autoforyou`) => {
  const httpLink = createHttpLink({
    uri: `网址`,
    headers: {
     
    },

  })
  
  const wsLink = new WebSocketLink({
    uri: `ws网址`,
    options: {
      reconnect: true,
      connectionParams: {
        headers: {
          "这里写token",
        }
      }
    }
  });

正在实例化一个WebSocketLink知道订阅端点的。在这种情况下,订阅点类似于HTTP终结点,不同之处在于它使用ws而不是http协议。使用token从中检索到的用户身份验证websocket连接localStorage

  const client = new ApolloClient({
    link,
    cache,
    
  });

实例化APolloClient

2. 订阅模式

在想要进行订阅的地方放入subscribeToMore

  <Query query={FEED_QUERY}>
        {({ loading, error, data, subscribeToMore }) => {
            
        }}
 </Query>

订阅模式的查询语句

const NEW_LINKS_SUBSCRIPTION = gql`
subscription MySubscription {
 customer {
   customer_name
   updated_at
   customer_source
   customer_tel
   id
   customer_phone
   industry {
     name
   }
   level {
     level_name
     id
   }
 }
}

通过调用其各自的函数,可以确保该组件确实订阅了事件

  <Query query={FEED_QUERY}>
        {({ loading, error, data, subscribeToMore }) => {
             this._subscribeToNewLinks(subscribeToMore)

        }}
 </Query>

将两个参数传递给subscribeToMore

  _subscribeToNewLinks =subscribeToMore  => {
    
    subscribeToMore({
      document: NEW_LINKS_SUBSCRIPTION,//下面有解释
      updateQuery: (prev, { subscriptionData }) => {
        if (!subscriptionData.data) return prev;
        const newFeedItem = subscriptionData.data.customer;  
        console.log(newFeedItem)
       return Object.assign({}, prev, {
              customer: newFeedItem, ...prev.customer, //这里其实我不懂为啥我放在[]里就是一直重复的增加空白demo
               count: prev.customer.length + 1,
                __typename: prev.customer.__typename
            
  })
      }
    })
  }

document:这代表订阅查询本身。就您而言,每次创建新链接时,订阅都会触发。 updateQuery :updateQuery:类似于缓存update道具,此功能可让您确定如何使用事件发生后服务器发送的信息更新,在内部所做的全部工作updateQuery是从收到的链接中检索新链接subscriptionData,将其合并到现有链接列表中,并返回此操作的结果。

3. 后记

这里是我自己的总结从头到尾订阅的过程,如果发现错误,欢迎留言指出~

参考
1. Apollo官网: https://www.apollographql.com/docs/react/data/subscriptions/
2. 如何Graphql: https://www.howtographql.com/react-apollo/0-introduction/