網路層
為了知道如何存取您的 GraphQL 伺服器,Relay 要求開發人員在建立 Relay 環境實例時提供一個實作 INetwork
介面的物件。環境會使用此網路層來執行查詢、變更和(如果您的伺服器支援)訂閱。這允許開發人員使用最適合他們應用程式的任何傳輸方式(HTTP、WebSockets 等)和身份驗證,從而將環境與每個應用程式的網路配置的具體細節解耦。
目前,建立網路層最簡單的方法是透過 relay-runtime
套件中的輔助程式
import {
Environment,
Network,
RecordSource,
Store,
} from 'relay-runtime';
// Define a function that fetches the results of an operation (query/mutation/etc)
// and returns its results as a Promise:
function fetchQuery(
operation,
variables,
cacheConfig,
uploadables,
) {
return fetch('/graphql', {
method: 'POST',
headers: {
// Add authentication and other headers here
'content-type': 'application/json'
},
body: JSON.stringify({
query: operation.text, // GraphQL text from input
variables,
}),
}).then(response => {
return response.json();
});
}
// Create a network layer from the fetch function
const network = Network.create(fetchQuery);
const store = new Store(new RecordSource())
const environment = new Environment({
network,
store
// ... other options
});
export default environment;
請注意,這是一個基本範例,可幫助您入門。此範例可以擴展其他功能,例如請求/回應快取(例如,當 cacheConfig.force
為 false 時啟用)和上傳變更的表單資料(uploadables
參數)。
快取
Relay 儲存區會快取目前保留的查詢中的資料。請參閱導覽的重複使用快取資料章節。
這個頁面實用嗎?
請幫我們回答一些簡短問題,讓網站變得更好 回答幾個簡單的問題.