Storybook GraphiQL 擴充套件
Storybook GraphQL 擴充套件可用於在 Storybook 中顯示具有範例查詢的 GraphiQL IDE。
開始使用
首先,安裝擴充套件
yarn add @storybook/addon-graphql --dev
導入 setupGraphiQL
函式,並使用它建立帶有基本 URL 的 graphiql 輔助程式。
import { storiesOf } from '@storybook/react'
import { setupGraphiQL } from '@storybook/addon-graphql'
// setup the graphiql helper which can be used with the add method later
const graphiql = setupGraphiQL({ url: 'https://127.0.0.1:3000/graphql' });
storiesOf('GraphQL Demo', module)
.add('get user info', graphiql(`{
user(id: "1") {
name
}
}`));
提示:嘗試在另一個檔案中建立輔助程式,並從其中導入已設定的 graphiql 輔助程式
進階設定
setupGraphiQL
函式也接受 fetcher 參數,可用於變更 graphiql 取得資料的方式。如果未提供 fetcher 參數,它會建立一個使用 fetch
API 發出請求的 fetcher。上面的範例也可以使用自訂的 fetcher 來撰寫。
import { storiesOf } from '@storybook/react'
import { setupGraphiQL } from '@storybook/addon-graphql'
import { url } from './settings';
const fetcher = params => {
const options = {
method: 'post',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(params),
};
return fetch(url, options).then(res => res.json());
};
// create the helper with a custom fetcher
const graphiql = setupGraphiQL({ fetcher });
storiesOf('GraphQL Demo', module)
.add('get user info', graphiql(`{
user(id: "1") {
name
}
}`));