透過 100+ 技巧的合輯學習 Nuxt!

graphql-request
nuxt-graphql-request

輕鬆將極簡 GraphQL 用戶端整合至 Nuxt

nuxt-graphql-request

📡 GraphQL Request 模組

cinpm versionDependenciesnpm downloadscode style: prettierLicense: MIT

輕鬆將極簡 GraphQL 用戶端整合至 Nuxt.js。

功能特色

  • 簡單且輕量的 GraphQL 用戶端。
  • 基於 Promise 的 API(可搭配 async / await 使用)。
  • Typescript 支援。
  • AST 支援。
  • GraphQL Loader 支援。

📖 版本發佈說明📄 文件

設定

npx nuxi@latest module add graphql-request

針對 Nuxt2,請使用 nuxt-graphql-request v6


yarn add nuxt-graphql-request@v6 graphql --dev

nuxt.config.js

module.exports = {
  modules: ['nuxt-graphql-request'],

  build: {
    transpile: ['nuxt-graphql-request'],
  },

  graphql: {
    /**
     * An Object of your GraphQL clients
     */
    clients: {
      default: {
        /**
         * The client endpoint url
         */
        endpoint: 'https://swapi-graphql.netlify.com/.netlify/functions/index',
        /**
         * Per-client options overrides
         * See: https://github.com/prisma-labs/graphql-request#passing-more-options-to-fetch
         */
        options: {},
      },
      secondClient: {
        // ...client config
      },
      // ...your other clients
    },

    /**
     * Options
     * See: https://github.com/prisma-labs/graphql-request#passing-more-options-to-fetch
     */
    options: {
      method: 'get', // Default to `POST`
    },

    /**
     * Optional
     * default: false (this includes graphql-tag for node_modules folder)
     */
    includeNodeModules: true,
  },
};

執行階段設定

如果您需要在執行階段而非建置階段提供端點,您可以使用執行階段設定來提供您的值

nuxt.config.js

module.exports = {
  publicRuntimeConfig: {
    graphql: {
      clients: {
        default: {
          endpoint: '<client endpoint>',
        },
        secondClient: {
          endpoint: '<client endpoint>',
        },
        // ...more clients
      },
    },
  },
};

TypeScript

類型定義應可直接運作。您應該已設定 Typescript 以擴充 Nuxt 的自動產生設定。若否,您可以從這裡開始

tsconfig.json
{
  "extends": "./.nuxt/tsconfig.json"
}

用法

元件

useAsyncData

<script setup>
import { gql } from 'nuxt-graphql-request/utils';

const { $graphql } = useNuxtApp();

const query = gql`
  query planets {
    allPlanets {
      planets {
        id
        name
      }
    }
  }
`;

const { data: planets } = await useAsyncData('planets', async () => {
  const data = await $graphql.default.request(query);
  return data.allPlanets.planets;
});
</script>

使用者定義函式

<script setup>
import { gql } from 'nuxt-graphql-request/utils';

const { $graphql } = useNuxtApp();

const query = gql`
  query planets {
    allPlanets {
      planets {
        id
        name
      }
    }
  }
`;

const planets = ref([])

const fetchPlanets = () => {
  const data = await $graphql.default.request(query);
  planets.value = data.allPlanets.planets;
}
</script>

Store actions

import { defineStore } from 'pinia';
import { gql } from 'nuxt-graphql-request/utils';
import { useNuxtApp } from '#imports';

type Planet = { id: number; name: string };

export const useMainStore = defineStore('main', {
  state: () => ({
    planets: null as Planet[] | null,
  }),
  actions: {
    async fetchAllPlanets() {
      const query = gql`
        query planets {
          allPlanets {
            planets {
              id
              name
            }
          }
        }
      `;

      const data = await useNuxtApp().$graphql.default.request(query);
      this.planets = data.allPlanets.planets;
    },
  },
});

GraphQL Request 用戶端

範例,取自官方 graphql-request 函式庫。

透過 HTTP 標頭進行身分驗證

nuxt.config.ts
export default defineNuxtConfig({
  graphql: {
    clients: {
      default: {
        endpoint: 'https://swapi-graphql.netlify.com/.netlify/functions/index',
        options: {
          headers: {
            authorization: 'Bearer MY_TOKEN',
          },
        },
      },
    },
  },
});
逐步設定標頭

如果您想在 GraphQLClient 初始化後設定標頭,可以使用 setHeader()setHeaders() 函式。

const { $graphql } = useNuxtApp();

// Override all existing headers
$graphql.default.setHeaders({ authorization: 'Bearer MY_TOKEN' });

// Set a single header
$graphql.default.setHeader('authorization', 'Bearer MY_TOKEN');
設定端點

如果您想在 GraphQLClient 初始化後變更端點,可以使用 setEndpoint() 函式。

const { $graphql } = useNuxtApp();

$graphql.default.setEndpoint(newEndpoint);
passing-headers-in-each-request

可以為每個請求傳遞自訂標頭。request()rawRequest() 接受標頭物件作為第三個參數

<script setup>
import { gql } from 'nuxt-graphql-request/utils';

const { $graphql } = useNuxtApp();

const requestHeaders = {
  authorization: 'Bearer MY_TOKEN',
};

const planets = ref();

const fetchSomething = async () => {
  const query = gql`
    query planets {
      allPlanets {
        planets {
          id
          name
        }
      }
    }
  `;

  // Overrides the clients headers with the passed values
  const data = await $graphql.default.request(query, {}, requestHeaders);
  planets.value = data.allPlanets.planets;
};
</script>

傳遞更多選項至 fetch

nuxt.config.ts
export default defineNuxtConfig({
  graphql: {
    clients: {
      default: {
        endpoint: 'https://swapi-graphql.netlify.com/.netlify/functions/index',
        options: {
          credentials: 'include',
          mode: 'cors',
        },
      },
    },
  },
});

或使用 setHeaders / setHeader

const { $graphql } = useNuxtApp();

// Set a single header
$graphql.default.setHeader('credentials', 'include');
$graphql.default.setHeader('mode', 'cors');

// Override all existing headers
$graphql.default.setHeaders({
  credentials: 'include',
  mode: 'cors',
});

使用 GraphQL 文件變數

<script setup>
import { gql } from 'nuxt-graphql-request/utils';

const { $graphql } = useNuxtApp();

const fetchSomething = async () => {
  const query = gql`
    query planets($first: Int) {
      allPlanets(first: $first) {
        planets {
          id
          name
        }
      }
    }
  `;

  const variables = { first: 10 };

  const planets = await this.$graphql.default.request(query, variables);
};
</script>

錯誤處理

<script setup>
import { gql } from 'nuxt-graphql-request/utils';

const { $graphql } = useNuxtApp();

const fetchSomething = async () => {
  const mutation = gql`
    mutation AddMovie($title: String!, $releaseDate: Int!) {
      insert_movies_one(object: { title: $title, releaseDate: $releaseDate }) {
        title
        releaseDate
      }
    }
  `;

  const variables = {
    title: 'Inception',
    releaseDate: 2010,
  };

  const data = await $graphql.default.request(mutation, variables);
};
</script>

GraphQL Mutations

<script setup>
import { gql } from 'nuxt-graphql-request/utils';

const { $graphql } = useNuxtApp();

const fetchSomething = async () => {
  const query = gql`
    {
      Movie(title: "Inception") {
        releaseDate
        actors {
          fullname # "Cannot query field 'fullname' on type 'Actor'. Did you mean 'name'?"
        }
      }
    }
  `;

  try {
    const data = await $graphql.default.request(query);
    console.log(JSON.stringify(data, undefined, 2));
  } catch (error) {
    console.error(JSON.stringify(error, undefined, 2));
    process.exit(1);
  }
};
</script>

接收原始回應

request 方法將傳回回應中的 dataerrors 鍵。如果您需要存取 extensions 鍵,可以使用 rawRequest 方法

import { gql } from 'nuxt-graphql-request/utils';

const { $graphql } = useNuxtApp();

const query = gql`
  query planets($first: Int) {
    allPlanets(first: $first) {
      planets {
        id
        name
      }
    }
  }
`;

const variables = { first: 10 };

const { data, errors, extensions, headers, status } = await $graphql.default.rawRequest(
  endpoint,
  query,
  variables
);
console.log(JSON.stringify({ data, errors, extensions, headers, status }, undefined, 2));

批次查詢

<script setup>
const { $graphql } = useNuxtApp();

const fetchSomething = async () => {
  const query1 = /* GraphQL */ `
    query ($id: ID!) {
      capsule(id: $id) {
        id
        landings
      }
    }
  `;

  const variables1 = {
    id: 'C105',
  };

  const query2 = /* GraphQL */ `
    {
      rockets(limit: 10) {
        active
      }
    }
  `;

  const query3 = /* GraphQL */ `
    query ($id: ID!) {
      core(id: $id) {
        id
        block
        original_launch
      }
    }
  `;

  const variables3 = {
    id: 'B1015',
  };

  try {
    const data = await $graphql.default.batchRequests([
      { document: query1, variables: variables1 },
      { document: query2 },
      { document: query3, variables: variables3 },
    ]);

    console.log(JSON.stringify(data, undefined, 2));
  } catch (error) {
    console.error(JSON.stringify(error, undefined, 2));
    process.exit(1);
  }
};
</script>

取消

可以使用 AbortController signal 取消請求。

<script setup>
import { gql } from 'nuxt-graphql-request/utils';

const { $graphql } = useNuxtApp();

const fetchSomething = async () => {
  const query = gql`
    query planets {
      allPlanets {
        planets {
          id
          name
        }
      }
    }
  `;

  const abortController = new AbortController();

  const planets = await $graphql.default.request({
    document: query,
    signal: abortController.signal,
  });

  abortController.abort();
};
</script>

在 Node 環境中,自 v14.17.0 版本起支援 AbortController。針對 Node.js v12,您可以使用 abort-controller polyfill。

import 'abort-controller/polyfill';

const abortController = new AbortController();

中介軟體

可以使用中介軟體預先處理任何請求或處理原始回應。

請求 & 回應中介軟體範例(將實際授權權杖設定至每個請求,並在發生錯誤時記錄請求追蹤 ID)

function requestMiddleware(request: RequestInit) {
  const token = getToken();
  return {
    ...request,
    headers: { ...request.headers, 'x-auth-token': token },
  };
}

function responseMiddleware(response: Response<unknown>) {
  if (response.errors) {
    const traceId = response.headers.get('x-b3-traceid') || 'unknown';
    console.error(
      `[${traceId}] Request error:
        status ${response.status}
        details: ${response.errors}`
    );
  }
}

export default defineNuxtConfig({
  modules: ['nuxt-graphql-request'],

  graphql: {
    /**
     * An Object of your GraphQL clients
     */
    clients: {
      default: {
        /**
         * The client endpoint url
         */
        endpoint: 'https://swapi-graphql.netlify.com/.netlify/functions/index',
        /**
         * Per-client options overrides
         * See: https://github.com/prisma-labs/graphql-request#passing-more-options-to-fetch
         */
        options: {
          requestMiddleware: requestMiddleware,
          responseMiddleware: responseMiddleware,
        },
      },

      // ...your other clients
    },

    /**
     * Options
     * See: https://github.com/prisma-labs/graphql-request#passing-more-options-to-fetch
     */
    options: {
      method: 'get', // Default to `POST`
    },

    /**
     * Optional
     * default: false (this includes graphql-tag for node_modules folder)
     */
    includeNodeModules: true,
  },
});

FAQ

為何選用 nuxt-graphql-request 而非 @nuxtjs/apollo

別誤會,Apollo Client 很棒,且由 vue / nuxt 社群良好維護,在切換至 graphql-request 之前,我使用了 Apollo Client 18 個月。

然而,由於我對效能非常在意,Apollo Client 完全不符合我的需求

  • 我不需要另一個狀態管理工具,因為 Vue 生態系統已足夠(Vuex & Persisted data)。
  • 我不需要在我的應用程式中額外解析約 120kb 的大小來擷取我的資料。
  • 我不需要訂閱功能,因為我使用 pusher.com,也有其他 WS 用戶端替代方案:http://github.com/lunchboxer/graphql-subscriptions-client

為何我必須安裝 graphql

graphql-request 使用來自 graphql 套件的 TypeScript 類型,因此,如果您使用 TypeScript 來建置專案,而且您使用 graphql-request 但未安裝 graphql,TypeScript 建置將會失敗。詳情請參閱此處。如果您是 JS 使用者,那麼技術上您不需要安裝 graphql。然而,如果您使用的 IDE 會擷取 JS 的 TS 類型(例如 VSCode),那麼為了在開發期間受益於更強的類型安全,您仍然有必要安裝 graphql

我是否需要將我的 GraphQL 文件包裝在 graphql-request 匯出的 gql 範本中?

否。它在那裡是為了方便起見,讓您可以獲得工具支援,例如更漂亮的格式設定和 IDE 語法突顯。如果您因為某些原因需要,您也可以從 graphql-tag 使用 gql

graphql-request、Apollo 和 Relay 之間有何差異?

graphql-request 是最極簡且最易於使用的 GraphQL 用戶端。它非常適合小型腳本或簡單的應用程式。

與 Apollo 或 Relay 等 GraphQL 用戶端相比,graphql-request 沒有內建快取,也沒有前端框架的整合。目標是盡可能保持套件和 API 的極簡性。

nuxt-graphql-request 是否支援 mutations?

當然,您可以像以前一樣執行任何 GraphQL 查詢 & mutations 👍

開發

  1. 複製此儲存庫
  2. 使用 yarn installnpm install 安裝相依性
  3. 使用 yarn devnpm run dev 啟動開發伺服器

Roadmap

📑 授權條款

MIT 授權條款