跳到主要內容

GraphQL

GraphQL 是一種 API 的查詢語言。它通常被用作 RESTful APIs 的替代方案,但也可以用作現有 RESTful 服務之上的額外「閘道」層。

使用 Prisma ORM,您可以建構連接到資料庫的 GraphQL 伺服器。Prisma ORM 完全獨立於您使用的 GraphQL 工具。在建構 GraphQL 伺服器時,您可以將 Prisma ORM 與 Apollo Server、GraphQL Yoga、TypeGraphQL、GraphQL.js 等工具,或幾乎任何您在 GraphQL 伺服器設定中使用的工具或函式庫結合使用。

GraphQL 伺服器的底層原理

一個 GraphQL 伺服器由兩個主要組件組成

  • GraphQL schema (類型定義 + resolvers)
  • HTTP 伺服器

請注意,GraphQL schema 可以用 code-first 或 SDL-first 方式編寫。請查看這篇 文章 以了解更多關於這兩種方法的資訊。如果您喜歡 SDL-first 方法,但仍然希望您的程式碼具有型別安全,請查看 GraphQL Code Generator 以根據 SDL 生成各種型別定義。

GraphQL schema 和 HTTP 伺服器通常由不同的函式庫處理。以下是目前 GraphQL 伺服器工具及其用途的概觀

函式庫 (npm 套件)用途與 Prisma ORM 相容Prisma 整合
graphqlGraphQL schema (code-first)
graphql-toolsGraphQL schema (SDL-first)
type-graphqlGraphQL schema (code-first)typegraphql-prisma
nexusGraphQL schema (code-first)nexus-prisma 早期預覽
apollo-serverHTTP 伺服器不適用
express-graphqlHTTP 伺服器不適用
fastify-gqlHTTP 伺服器不適用
graphql-yogaHTTP 伺服器不適用

除了這些獨立和單一用途的函式庫之外,還有幾個專案正在建構整合式應用程式框架

框架技術堆疊建立者Prisma ORM描述
Redwood.js全端Tom Preston-Werner基於 Prisma ORM 建構將全端帶入 JAMstack。

注意:如果您發現列表中缺少任何 GraphQL 函式庫/框架,請告知我們。

Prisma ORM 與 GraphQL 範例

在以下章節中,您將找到幾個可立即執行的範例,展示如何將 Prisma ORM 與上表中提到的工具的不同組合一起使用。

範例HTTP 伺服器GraphQL schema描述
GraphQL API (Pothos)graphql-yogapothos基於 graphql-yoga 的 GraphQL 伺服器
GraphQL API (SDL-first)graphql-yoga不適用基於 SDL-first 方法的 GraphQL 伺服器
GraphQL API -- NestJs@nestjs/apollo不適用基於 NestJS 的 GraphQL 伺服器
GraphQL API -- NestJs (SDL-first)@nestjs/apollo不適用基於 NestJS 的 GraphQL 伺服器
GraphQL API (Nexus)@apollo/servernexus基於 @apollo/server 的 GraphQL 伺服器
GraphQL API (TypeGraphQL)apollo-servertype-graphql基於 TypeGraphQL 的 code-first 方法的 GraphQL 伺服器
GraphQL API (Auth)apollo-servernexus具有電子郵件密碼驗證和權限的 GraphQL 伺服器
全端應用程式graphql-yogapothos使用 Next.js (React)、Apollo Client、GraphQL Yoga 和 Pothos 的全端應用程式
GraphQL 訂閱apollo-servernexus實作即時 GraphQL 訂閱的 GraphQL 伺服器
GraphQL API -- Hapiapollo-server-hapinexus基於 Hapi 的 GraphQL 伺服器
GraphQL API -- Hapi (SDL-first)apollo-server-hapigraphql-tools基於 Hapi 的 GraphQL 伺服器
GraphQL API -- Fastifyfastifymercurius不適用基於 FastifyMercurius 的 GraphQL 伺服器
GraphQL API -- Fastify (SDL-first)fastifyNexus基於 FastifyMercurius 的 GraphQL 伺服器

常見問題

Prisma ORM 在 GraphQL 伺服器中的角色是什麼?

無論您使用上述哪種 GraphQL 工具/函式庫,Prisma ORM 都會在您的 GraphQL resolvers 內部使用,以連接到您的資料庫。它扮演的角色與任何其他 ORM 或 SQL query builder 在您的 resolvers 內部扮演的角色相同。

在 GraphQL query 的 resolver 中,Prisma ORM 通常從資料庫讀取資料,以便在 GraphQL response 中返回。在 GraphQL mutation 的 resolver 中,Prisma ORM 通常也會將資料寫入資料庫(例如,建立新記錄或更新現有記錄)。

其他 GraphQL 資源

Prisma 策劃了 GraphQL Weekly,這是一份強調 GraphQL 社群資源和更新的電子報。訂閱以隨時掌握 GraphQL 文章、影片、教學、函式庫等最新資訊。