GraphQL LogoGraphQL

建構類型

對於許多應用程式,你可以在應用程式啟動時定義一個固定的架構,並使用 GraphQL 架構語言定義它。在某些情況下,以程式化方式建構架構會很有用。你可以使用 GraphQLSchema 建構函數來執行此操作。

當你使用 GraphQLSchema 建構函數建立架構時,不是僅使用架構語言定義 QueryMutation 類型,而是將它們建立為獨立的物件類型。

例如,假設我們正在建立一個簡單的 API,讓你根據 id 取得幾個硬編碼使用者的使用者資料。使用 buildSchema,我們可以用以下方式撰寫伺服器

var express = require("express")
var { createHandler } = require("graphql-http/lib/use/express")
var { buildSchema } = require("graphql")
var schema = buildSchema(`
type User {
id: String
name: String
}
type Query {
user(id: String): User
}
`)
// Maps id to User object
var fakeDatabase = {
a: {
id: "a",
name: "alice",
},
b: {
id: "b",
name: "bob",
},
}
var root = {
user: ({ id }) => {
return fakeDatabase[id]
},
}
var app = express()
app.all(
"/graphql",
createHandler({
schema: schema,
rootValue: root,
})
)
app.listen(4000)
console.log("Running a GraphQL API server at localhost:4000/graphql")

我們可以不使用 GraphQL 架構語言實作相同的 API

var express = require("express")
var { createHandler } = require("graphql-http/lib/use/express")
var graphql = require("graphql")
// Maps id to User object
var fakeDatabase = {
a: {
id: "a",
name: "alice",
},
b: {
id: "b",
name: "bob",
},
}
// Define the User type
var userType = new graphql.GraphQLObjectType({
name: "User",
fields: {
id: { type: graphql.GraphQLString },
name: { type: graphql.GraphQLString },
},
})
// Define the Query type
var queryType = new graphql.GraphQLObjectType({
name: "Query",
fields: {
user: {
type: userType,
// `args` describes the arguments that the `user` query accepts
args: {
id: { type: graphql.GraphQLString },
},
resolve: (_, { id }) => {
return fakeDatabase[id]
},
},
},
})
var schema = new graphql.GraphQLSchema({ query: queryType })
var app = express()
app.all(
"/graphql",
createHandler({
schema: schema,
})
)
app.listen(4000)
console.log("Running a GraphQL API server at localhost:4000/graphql")

當我們使用這種方法建立 API 時,根層級解析器會實作在 QueryMutation 類型上,而不是在 root 物件上。

如果你想從其他地方自動建立 GraphQL 架構,例如資料庫架構,這將特別有用。你可能有一個通用的格式,用於建立和更新資料庫記錄。這對於實作無法直接對應到 ES6 類別和架構語言的聯合類型等功能也很有用。

繼續閱讀 →graphql-http