• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

TypeScript apollo-link.split函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了TypeScript中apollo-link.split函数的典型用法代码示例。如果您正苦于以下问题:TypeScript split函数的具体用法?TypeScript split怎么用?TypeScript split使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了split函数的5个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的TypeScript代码示例。

示例1: createClient

export function createClient(
  // @ts-ignore - useful to pass in the store for `Authorization` headers, etc
  store: Store
): ApolloClient<NormalizedCacheObject> {
  // Create the cache first, which we'll share across Apollo tooling.
  // This is an in-memory cache. Since we'll be calling `createClient` on
  // universally, the cache will survive until the HTTP request is
  // responded to (on the server) or for the whole of the user's visit (in
  // the browser)
  const cache = new InMemoryCache({ fragmentMatcher });

  // Create a HTTP client (both server/client). It takes the GraphQL
  // server from the `GRAPHQL` environment variable, which by default is
  // set to an external playground at https://graphqlhub.com/graphql
  const httpLink = new HttpLink({
    credentials: "same-origin",
    uri: GRAPHQL
  });

  // If we're in the browser, we'd have received initial state from the
  // server. Restore it, so the client app can continue with the same data.
  if (!SERVER) {
    cache.restore((window as any).__APOLLO__);
  }

  // Return a new Apollo Client back, with the cache we've just created,
  // and an array of 'links' (Apollo parlance for GraphQL middleware)
  // to tell Apollo how to handle GraphQL requests
  return new ApolloClient({
    cache,
    link: ApolloLink.from([
      // General error handler, to log errors back to the console.
      // Replace this in production with whatever makes sense in your
      // environment. Remember you can use the global `SERVER` variable to
      // determine whether you're running on the server, and record errors
      // out to third-party services, etc
      onError(({ graphQLErrors, networkError }) => {
        if (graphQLErrors) {
          graphQLErrors.map(({ message, locations, path }) =>
            console.log(
              `[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`
            )
          );
        }
        if (networkError) {
          console.log(`[Network error]: ${networkError}`);
        }
      }),

      // Split on HTTP and WebSockets
      WS_SUBSCRIPTIONS && !SERVER
        ? split(
            ({ query }) => {
              const definition = getMainDefinition(query);
              return (
                definition.kind === "OperationDefinition" &&
                definition.operation === "subscription"
              );
            },
            // Use WebSockets for subscriptions
            new WebSocketLink(
              // Replace http(s) with `ws` for connecting via WebSockts
              new SubscriptionClient(GRAPHQL.replace(/^https?/, "ws"), {
                reconnect: true // <-- automatically redirect as needed
              })
            ),
            // ... fall-back to HTTP for everything else
            httpLink
          )
        : httpLink // <-- just use HTTP on the server
    ]),
    // On the server, enable SSR mode
    ssrMode: SERVER
  });
}
开发者ID:leebenson,项目名称:cli,代码行数:75,代码来源:apollo.ts


示例2: WebSocketLink

});

const wsLink = new WebSocketLink({
  options: {
    connectionParams: {
      "X-JWT": getToken()
    },
    reconnect: true
  },
  uri: "ws://localhost:4000/subscription"
});

const combinedLinks = split(
  ({ query }) => {
    const { kind, operation }: any = getMainDefinition(query);
    return kind === "OperationDefinition" && operation === "subscription";
  },
  wsLink,
  httpLink
);

const errorLink = onError(({ graphQLErrors, networkError }) => {
  if (graphQLErrors) {
    graphQLErrors.map(({ message }) => {
      toast.error(`Unexpected error: ${message}`);
    });
  }
  if (networkError) {
    toast.error(`Network error: ${networkError}`);
  }
});
开发者ID:piann,项目名称:weber-client,代码行数:31,代码来源:apollo.ts


示例3: WebSocketLink

// Create a WebSocket link:
const wsLink = new WebSocketLink({
  uri: `${ssl ? 'wss' : 'ws'}://${host}/subscriptions`,
  options: {
    reconnect: true,
  },
})

// using the ability to split links, you can send data to each link
// depending on what kind of operation is being sent
const link = split(
  // split based on operation type
  ({query}) => {
    const {kind, operation} = getMainDefinition(
      query,
    ) as OperationDefinitionNode
    return kind === 'OperationDefinition' && operation === 'subscription'
  },
  wsLink,
  httpLink,
)

const cache = new InMemoryCache({
  cacheRedirects: {
    Query: {
      device: (_, args) =>
        toIdValue(
          cache.config.dataIdFromObject({__typename: 'Device', id: args.id}),
        ),
    },
  },
开发者ID:Pajn,项目名称:RAXA,代码行数:31,代码来源:store.ts


示例4: setContext

})

const authLink = setContext((_, { headers }) => {
  const auth = getAuthHeader()

  return {
    headers: {
      ...headers,
      Authorization: auth,
    },
  }
})

const terminatingLink = split(
  ({ query }) => {
    const { kind, operation } = getMainDefinition(query) as OperationDefinitionNode
    return kind === 'OperationDefinition' && operation === 'subscription'
  },
  wsLink,
  authLink.concat(httpLink),
)

const link = ApolloLink.from([terminatingLink])

const cache = new InMemoryCache()

export default new ApolloClient({
  link,
  cache,
})
开发者ID:,项目名称:,代码行数:30,代码来源:


示例5: createApolloClient

export function createApolloClient() {
  const graphqlApiUrl = getGraphQLEndpoint(
    process.env.REACT_APP_LOCAL_API ? 'graphqlApiUrlLocal' : 'graphqlApiUrl',
  );

  const httpLink = createHttpLink({ uri: graphqlApiUrl });
  const authLink = setContext((_, { headers }) => {
    return {
      headers: {
        ...headers,
        authorization: appInitializer.getBearerToken() || null,
      },
    };
  });

  const subscriptionsApiUrl = getGraphQLEndpoint(
    process.env.REACT_APP_LOCAL_API
      ? 'subscriptionsApiUrlLocal'
      : 'subscriptionsApiUrl',
  );
  const wsLink = new WebSocketLink({
    uri: subscriptionsApiUrl,
    options: {
      reconnect: true,
    },
  });
  const cache = new InMemoryCache();

  const authHttpLink = authLink.concat(httpLink);
  const errorLink = onError(
    ({ operation, response, graphQLErrors, networkError }) => {
      if (process.env.REACT_APP_ENV !== 'production') {
        if (graphQLErrors) {
          graphQLErrors.map(({ message, locations, path }) =>
            // tslint:disable-next-line
            console.error(
              `[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`,
            ),
          );
        }

        // tslint:disable-next-line
        if (networkError) console.error(`[Network error]: ${networkError}`);
      }
    },
  );
  const link = split(
    ({ query }) => {
      const { kind, operation } = getMainDefinition(query);
      return kind === 'OperationDefinition' && operation === 'subscription';
    },
    wsLink,
    authHttpLink,
  );

  const client = new ApolloClient({
    link: ApolloLink.from([errorLink, link]),
    cache,
    connectToDevTools: true,
  });

  return client;
}
开发者ID:marynaKhromova,项目名称:console,代码行数:63,代码来源:apollo-client.ts



注:本文中的apollo-link.split函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
TypeScript apollo-link.ApolloLink类代码示例发布时间:2022-05-25
下一篇:
TypeScript apollo-link.fromError函数代码示例发布时间:2022-05-25
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap