如何使用 svelte 进行 graphql 和 graphql 订阅

How to do graphql and graphql subscriptions with svelte

为了进行 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);

我正在使用 urql's svelte bindings. The documentation also shows how to use the bindings with subscriptions