graphql - 如何使用 svelte 进行 graphql 和 graphql 订阅
问题描述
要进行 graphql 查询和突变,我在 fetch 和 svelte-apollo 上都取得了成功(参见https://github.com/timhall/svelte-apollo)
我喜欢 fech 方法的简单性。
Svelte-apollo 具有订阅功能,我会尝试让它工作。
但是有替代品吗?
您如何使用 svelte 使用 graphql 订阅?
解决方案
这是我的解决方案,使用 Apollo:
import { ApolloClient } from 'apollo-client';
import { InMemoryCache } from 'apollo-cache-inmemory';
import { HttpLink } from 'apollo-link-http';
import { WebSocketLink } from 'apollo-link-ws';
import { split } from 'apollo-link';
import { getMainDefinition } from 'apollo-utilities';
const httpLink = new HttpLink({
uri: 'http://localhost:3000/graphql'
});
const wsLink = new WebSocketLink({
uri: `ws://localhost:3000/subscriptions`,
options: {
reconnect: true
}
});
const link = split(
// split based on operation type
({ query }) => {
const definition = getMainDefinition(query);
return (
definition.kind === 'OperationDefinition' &&
definition.operation === 'subscription'
);
},
wsLink,
httpLink,
);
const client = new ApolloClient({
link,
cache: new InMemoryCache()
});
毕竟,您已经设置了客户端。下一个,
import gql from 'graphql-tag';
client.subscribe({
query: gql`subscription { whatever }`
}).subscribe(result => console.log(result.data);
推荐阅读
- shell - 用于显示给定数字范围内的完美数字的 Shell 脚本
- javascript - 具有条件渲染子级的动画组件
- python - Azure Blob 触发 Python 函数写入 CosmosDB 错误
- php - 如何定位帖子数组以制作一行代码而不是多行代码?
- javascript - 我怎么能没有背景颜色扩展整个容器?
- docker - 如何在 jenkins + docker + kubernetes localy 上运行
- sql - 有些人有几个单独的策略我如何过滤数据,所以我只能看到每个电子邮件地址的最近联系日期?
- flutter - Flutter Firestore 异步函数/等待结果
- react-native - 反应原生地图标记不显示?
- javascript - 博主 | 为什么我的 javascript 代码只显示一篇文章?