概要
urqlはGraphQLクライアントライブラリです。拡張性と柔軟性に優れており軽量に設計されています。
核となる概念に exchanges があります。exchanges は GraphQL リクエストとレスポンスの処理フローを制御するミドルウェアのような仕組みです。
基本概念
パイプラインアーキテクチャ
- Exchange は配列として Client に渡されて、上から順に処理のパイプラインを形成する
- 各 Exchange は、次の Exchange に処理を渡すための forward 関数を受け取る
OperationとOperationResult
- オペレーション(リクエスト)はパイプラインを下方向(App → API)に流れ、結果(レスポンス)は上方向(API → App)に流れます
- パイプラインを流れるデータはOperationオブジェクト(クエリ、変数、コンテキスト情報など)
- パイプラインから返ってくるデータはOperationResultオブジェクト(dataやerrorなど)
exchangesの種類
cacheExchange
Document Cachingを使用しGraphQLの結果をキャッシュします
import { createClient, cacheExchange, fetchExchange } from 'urql';
const client = createClient({
url: 'http://localhost:3000/graphql',
exchanges: [
cacheExchange, <-キャッシュ
fetchExchange,
],
});
fetchExchange
HTTP fetchを実行して GraphQL の結果を取得します
import { createClient, cacheExchange, fetchExchange } from 'urql';
const client = createClient({
url: 'http://localhost:3000/graphql',
exchanges: [
cacheExchange,
fetchExchange, <- 実行
],
});
authExchange
認証フローを簡単にします。下記 config... の中でエラーハンドリングやrefreshの設定を行います。
import { createClient, cacheExchange, fetchExchange } from 'urql';
import { authExchange } from '@urql/exchange-auth';
const client = createClient({
url: 'http://localhost:3000/graphql',
exchanges: [
cacheExchange,
authExchange(async utils => {
return {
/* config... */
};
}),
fetchExchange,
],
});
retryExchange
エラー時に再度トライする機能です。
exchangeの順番が重要で cacheExchangeの後であり、fetchExchangeより前に配置する必要があります。
import { createClient, cacheExchange, fetchExchange } from 'urql';
import { retryExchange } from '@urql/exchange-retry';
const options = {
initialDelayMs: 1000,
maxDelayMs: 15000,
randomDelay: true,
maxNumberAttempts: 2,
retryIf: err => err && err.networkError,
};
const client = createClient({
url: 'http://localhost:1234/graphql',
exchanges: [
cacheExchange,
retryExchange(options),
fetchExchange,
],
});
subscriptionExchange
リアルタイムにデータを購読するときに使用します
graphql-wsを使用した例
import { createClient, cacheExchange, fetchExchange, subscriptionExchange } from 'urql';
import { createClient as createWSClient } from 'graphql-ws';
const wsClient = createWSClient({
url: 'ws://localhost/graphql',
});
const client = createClient({
url: '/graphql',
exchanges: [
cacheExchange,
fetchExchange,
subscriptionExchange({
forwardSubscription(request) {
const input = { ...request, query: request.query || '' };
return {
subscribe(sink) {
const unsubscribe = wsClient.subscribe(input, sink);
return { unsubscribe };
},
};
},
}),
],
});
他にも種類があるので公式を確認ください。