如何在Svelte中使用GraphQL和GraphQL订阅

6

为了进行graphql的查询和变异,我已经成功地使用了fetch和svelte-apollo(请参见https://github.com/timhall/svelte-apollo)。

我喜欢fetch方法的简单性。

Svelte-apollo具备订阅功能,我会尝试使其工作。

但是还有其他选择吗?

如何使用svelte消费graphql的订阅?


我也在寻找同样的建议。有什么消息吗? - Fred Hors
2个回答

7

这是我的解决方案,使用了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);

1
很好,即使没有使用sapper,你也可以做到这一点。距离你发布这个解决方案已经快一年了。如果今天你要写同样的解决方案,你会怎么写? - mojo2go

-1

网站上的示例无法运行。你有一个可用的示例吗? - Rushi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接