透過 100+ 個技巧學習 Nuxt!

nuxt-graphql-server

使用 Nuxt 輕鬆實作 GraphQL 伺服器

Nuxt 的 GraphQL 伺服器工具組

npm versionnpm downloadsGithub ActionsCodecov

此套件讓您可以在您的 Nuxt 3 應用程式中輕鬆開發 GraphQL 伺服器。

若要在客戶端使用 GraphQL API,我們推薦使用模組 Nuxt ApolloNuxt GraphQL Clientnuxt/graphql-client

功能

  • 提供虛擬模組 #graphql/schema,您可由此匯入您的 schema。在底層,它會自動將多個 schema 檔案合併成一個完整的 schema。此外,您不再需要擔心部署 schema graphql 檔案。
  • 透過虛擬模組 #graphql/resolver 自動為您的 resolvers 產生 typescript 定義。
  • 支援 GraphQL subscriptions。
  • Nuxt Devtools 整合:直接在 devtools 中加入 Apollo Studio Sandbox。

安裝

# nuxi
npx nuxi@latest module add graphql-server

# npm
npm install @apollo/server graphql @as-integrations/h3 nuxt-graphql-server

# yarn
yarn add @apollo/server graphql @as-integrations/h3 nuxt-graphql-server

# pnpm
pnpm add @apollo/server graphql @as-integrations/h3 nuxt-graphql-server

用法

  1. 若未使用 nuxi 進行安裝,請在 nuxt.config.ts 中加入模組
    export default defineNuxtConfig({
      modules: ['nuxt-graphql-server'],
      // Optional top-level config
      graphqlServer: {
        // config
      },
    })
    
    // or
    
    export default defineNuxtConfig({
      modules: [
        [
          'nuxt-graphql-server',
          {
            /* Optional inline config */
          },
        ],
      ],
    })
    
  2. 在位於 server 資料夾中的 .graphql 檔案中定義 GraphQL schema。
  3. 透過建立具有以下內容的 server/api/graphql.ts 來公開 GraphQL API endpoint
    import { Resolvers } from '#graphql/resolver'
    import { typeDefs } from '#graphql/schema'
    import { ApolloServer } from '@apollo/server'
    import { startServerAndCreateH3Handler } from '@as-integrations/h3'
    
    const resolvers: Resolvers = {
      Query: {
        // Typed resolvers
      },
    }
    
    const apollo = new ApolloServer({ typeDefs, resolvers })
    
    export default startServerAndCreateH3Handler(apollo, {
      // Optional: Specify context
      context: (event) => {
        /*...*/
      },
    })
    
  4. (可選)在 nuxt.config.ts 中指定 GraphQL endpoint 的(相對)網址,以啟用 Nuxt Devtools 整合。
    graphqlServer: {
       url: '/api/graphql',
    }
    

訂閱

若要啟用 subscriptions,您需要安裝一些額外依賴

# npm
npm install graphql-ws graphql-subscriptions

# yarn
yarn add graphql-ws graphql-subscriptions

# pnpm
pnpm add graphql-ws graphql-subscriptions

套件 graphql-ws 是一個輕量級 WebSocket 伺服器,可用於處理 GraphQL subscriptions。套件 graphql-subscriptions 提供了 PubSub 類別,可用於發布和訂閱事件。

請注意,預設的 PubSub 實作僅用於示範目的。它僅在您擁有伺服器的單一實例時有效,並且無法擴展到幾個以上的連線。對於生產環境使用,您會希望使用由外部儲存支援的 PubSub 實作之一。(例如 Redis)。

在您的 nuxt.config.ts 中啟用 websocket 支援

nitro: {
  experimental: {
    websocket: true,
  },
},

然後,建立具有以下內容的 endpoint server/api/graphql.ts

import { ApolloServer } from '@apollo/server'
import {
  startServerAndCreateH3Handler,
  defineGraphqlWebSocket,
} from '@as-integrations/h3'
import { makeExecutableSchema } from '@graphql-tools/schema'
import type { Resolvers } from '#graphql/resolver'
import { typeDefs } from '#graphql/schema'

const resolvers: Resolvers = {
  Query: {
    // Typed resolvers
  },
  Subscription: {
    // Typed resolvers
  },
}

const schema = makeExecutableSchema({ typeDefs, resolvers })
const apollo = new ApolloServer({ schema })
export default startServerAndCreateH3Handler(apollo, {
  websocket: defineGraphqlWebSocket({ schema }),
})

完整的範例可以在 playground 資料夾下的 server/api/subscription.ts 中找到。

選項

graphqlServer: {
  url: '/relative/path/to/your/graphql/endpoint',
  schema: './server/**/*.graphql',
  codegen: {
    maybeValue: T | null | undefined
  }
}

url

GraphQL Endpoint 的相對網址,用於啟用 Nuxt Devtools 整合。

schema

關於如何定位您的 GraphQL Schema (.graphql) 檔案的 glob 模式。

預設值:'./server/**/*.graphql'

codegen

此模組在底層使用 GraphQL Code Generator,並使用 TypeScriptTypeScript Resolvers 外掛程式,這表示來自這些外掛程式的任何選項都可以根據您的需求在此處傳遞。

例如,您可能想要

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

  graphqlServer: {
    codegen: {
      // Map your internal enum values to your GraphQL's enums.
      enumValues: '~/graphql/enums/index',

      // Make use of your custom GraphQL Context type and let codegen use it so that the
      // generated resolvers automatically makes use of it.
      contextType: '~/server/graphql/GraphQLContext#GraphQLContext',

      // Change the naming convention of your enum keys
      namingConvention: {
        enumValues: 'change-case-all#constantCase',
      },

      // ... and many more, refer to the plugin docs!
    },
  },
})

💻 開發

  • 複製此儲存庫
  • 使用 corepack enable 啟用 Corepack(Node.js < 16.10 請使用 npm i -g corepack)。
  • 使用 pnpm install 安裝依賴。
  • 執行 pnpm dev:prepare 以產生 type stubs。
  • 使用 pnpm dev 以開發模式啟動 playground。

授權條款

以 💛 製作

MIT 授權條款發布。