graphql-request
nuxt-graphql-request

將 Nuxt 與易於使用的極簡 GraphQL 客戶端整合

nuxt-graphql-request

📡 GraphQL 請求模組

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 請求客戶端

官方 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);
在每個請求中傳遞頭資訊

可以為每個請求傳遞自定義頭資訊。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 訊號取消請求。

<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 環境中,AbortController 自 v14.17.0 版本開始支援。對於 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,
  },
});

常見問題

為什麼使用 nuxt-graphql-request 而不是 @nuxtjs/apollo

別誤會,Apollo Client 很棒,並且由 Vue / Nuxt 社群維護得很好。我在切換到 graphql-request 之前使用了 Apollo Client 18 個月。

然而,我對效能非常著迷,Apollo Client 對我來說完全不適用。

  • 我不需要另一個狀態管理,因為 Vue 生態系統已經足夠(Vuex 和持久化資料)。
  • 我不需要在我的應用程式中解析額外的約 120kb 來獲取我的資料。
  • 我不需要訂閱,因為我使用 pusher.com,也有其他 WebSocket 客戶端替代方案:http://github.com/lunchboxer/graphql-subscriptions-client

為什麼我必須安裝 graphql

graphql-request 使用來自 graphql 包的 TypeScript 型別,因此如果您使用 TypeScript 構建專案並且正在使用 graphql-request 但未安裝 graphql,TypeScript 構建將失敗。詳細資訊請參閱此處。如果您是 JS 使用者,則在技術上不需要安裝 graphql。但是,如果您使用即使對於 JS 也支援 TS 型別的 IDE(例如 VSCode),那麼安裝 graphql 仍然對您有利,這樣您可以在開發過程中受益於增強的型別安全性。

我是否需要將我的 GraphQL 文件封裝在 graphql-request 匯出的 gql 模板中?

不需要。它只是為了方便,以便您獲得像 prettier 格式化和 IDE 語法高亮這樣的工具支援。如果您出於某種原因需要,也可以使用來自 graphql-taggql

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 啟動開發伺服器

路線圖

📑 許可證

麻省理工學院許可證