使用Hasura中的subscription(weixin公众号【图说GIS】)

安装库

 npm install @apollo/client  graphql  graphql-ws

创建客户端

import { ApolloClient, HttpLink, InMemoryCache, split } from '@apollo/client';
import { GraphQLWsLink } from '@apollo/client/link/subscriptions';
import { getMainDefinition } from '@apollo/client/utilities';
import { createClient } from 'graphql-ws';
export const graphqlUrl = 'http://x.x.x.x:x/v1/graphql'
export const wsGraphqlUrl = 'ws://x.x.x.x:x/v1/graphql'

const wsLink = new GraphQLWsLink(createClient({
    url: wsGraphqlUrl
}));

const httpLink = new HttpLink({
    uri: graphqlUrl
});

const splitLink = split(
    ({ query }) => {
        const definition = getMainDefinition(query);
        return (
            definition.kind === 'OperationDefinition' &&
            definition.operation === 'subscription'
        );
    },
    wsLink,
    httpLink,
);

export const client = new ApolloClient({
    link: splitLink,
    cache: new InMemoryCache()
});

使用

import { useSubscription } from "@apollo/client"
import { gql } from "@apollo/client"

const subscription = gql`
        subscription MySubscription {
        v_tag(where:{path:{_like:"1.%"}}) {name,oid,parentId}
        }
        `;
useSubscription(subscription , {
        onSubscriptionData: (datas) => {
            const { subscriptionData } = datas
            const data = subscriptionData.data
            const _datas = data.v_tag
            console.log(_datas )
        }
    })
或者
 function subscribe(datas) {
     const s= client.subscribe({
                query: subscription 
            }).subscribe(response => {
                const { data } = response;
               
            });
//取消  s.unsubscribe()
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值