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 自動為您的解析器生成 TypeScript 定義。
  • 支援 GraphQL 訂閱。
  • 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 端點。
    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 端點的(相對)URL,以啟用 Nuxt Devtools 整合。
    graphqlServer: {
       url: '/api/graphql',
    }
    

訂閱

要啟用訂閱,您需要安裝一些額外的依賴項。

# 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 訂閱。包 graphql-subscriptions 提供了 PubSub 類,可用於釋出和訂閱事件。

請注意,預設的 PubSub 實現僅用於演示目的。它僅在您擁有單個伺服器例項時才有效,並且無法擴充套件到少量連線之外。對於生產用途,您需要使用由外部儲存(例如 Redis)支援的 PubSub 實現之一。

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

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

然後,建立包含以下內容的端點 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 端點的相對 URL,用於啟用 Nuxt Devtools 整合。

schema

一個全域性模式,用於定位您的 GraphQL Schema (.graphql) 檔案。

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

程式碼生成

此模組底層使用 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 以生成型別存根。
  • 使用 pnpm dev 在開發模式下啟動 playground

許可證

用 💛 製作

根據 MIT 許可證釋出。