iT邦幫忙

2018 iT 邦幫忙鐵人賽
DAY 24
0
Data Technology

GraphQL + ApolloData 入門系列 第 25

ApolloData & ApolloLink

介紹

Apollo Link 是一種簡單而強大的方式來獲得 GraphQL 操作的結果,以及如何處理結果。

ApolloClient 提供了一個統一的 fetch 介面,每次請求graphql都會進到這裡來所以,URL 設定一次即可
ApolloData 2.0 後使用把傳往 graphql 的 link 包一層 HttpLink 這樣就可以在這一層獲取資料或分析Query的分析也可以獲得錯誤回報分析等等(1.0版是使用 createNetworkInterface 只有設定url)

import { ApolloLink } from 'apollo-link';
import { ApolloClient } from 'apollo-client';
import Cache from 'apollo-cache-inmemory';
import { HttpLink } from 'apollo-link-http';

const client = new ApolloClient({
  link: new HttpLink({ uri: 'http://api.githunt.com/graphql' }),
  cache: new Cache()
});

Apollo Link 也可以使用  graphql-tools 來結合遠端的 Schema


```javascript
import { HttpLink } from 'apollo-link-http';
import fetch from 'node-fetch';

const link = new HttpLink({ uri: 'http://api.githunt.com/graphql', fetch });

const schema = await introspectSchema(link);

const executableSchema = makeRemoteExecutableSchema({
  schema,
  link,
});

之前有介紹過在Server Part 使用 GraphiQL 這邊也可以在前端使用 透過 apollo-link-http
提供的 HttpLink 讓前端的 fetch 導向到 graphql endpoint

import React from 'react';
import ReactDOM from 'react-dom';
import '../node_modules/graphiql/graphiql.css'
import GraphiQL from 'graphiql';
import { parse } from 'graphql';

import { execute } from 'apollo-link';
import HttpLink from 'apollo-link-http';

const link = new HttpLink({
  uri: 'http://api.githunt.com/graphql'
});

const fetcher = (operation) => {
  operation.query = parse(operation.query);
  return execute(link, operation);
};

ReactDOM.render(
  <GraphiQL fetcher={fetcher}/>,
  document.body,
);

使用execute 或 makePromise 跑 單獨執行,不需要綁在元件裡面直接對 endpoint 發fetch
使用execute 會回傳一個Observable

import { execute, makePromise } from 'apollo-link';
import { HttpLink } from 'apollo-link-http';

const uri = 'http://api.githunt.com/graphql';
const link = new HttpLink({ uri });

// execute returns an Observable so it can be subscribed to
execute(link, operation).subscribe({
  next: data => console.log(`received data ${data}`),
  error: error => console.log(`received error ${error}`),
  complete: () => console.log(`complete`),
})

// For single execution operations, a Promise can be used
makePromise(execute(link, operation))
  .then(data => console.log(`received data ${data}`))
  .catch(error => console.log(`received error ${error}`))

總結

ApolloData 在 2.0 使用了 HttpLink 多一層這樣的包裝, 可以有更多擴展的功能


上一篇
ApolloData & Next.js (二)
下一篇
ApolloData & Engine
系列文
GraphQL + ApolloData 入門30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言