GraphQL.JS 文档
基本类型

在大多数情况下,你所需要做的就是使用 GraphQL 结构语言指定 API 的类型,并将其作为 buildSchema 函数的参数。

¥In most situations, all you need to do is to specify the types for your API using the GraphQL schema language, taken as an argument to the buildSchema function.

GraphQL 结构语言支持 StringIntFloatBooleanID 标量类型,因此你可以在传递给 buildSchema 的结构中直接使用这些类型。

¥The GraphQL schema language supports the scalar types of String, Int, Float, Boolean, and ID, so you can use these directly in the schema you pass to buildSchema.

默认情况下,每种类型都可以为空 - 返回 null 作为任何标量类型都是合法的。使用感叹号来指示类型不能为空,因此 String! 是一个不可为空的字符串。

¥By default, every type is nullable - it’s legitimate to return null as any of the scalar types. Use an exclamation point to indicate a type cannot be nullable, so String! is a non-nullable string.

要使用列表类型,请将类型括在方括号中,因此 [Int] 是整数列表。

¥To use a list type, surround the type in square brackets, so [Int] is a list of integers.

这些类型中的每一种都直接映射到 JavaScript,因此你可以在返回这些类型的 API 中返回普通的旧 JavaScript 对象。下面的示例展示了如何使用其中一些基本类型:

¥Each of these types maps straightforwardly to JavaScript, so you can just return plain old JavaScript objects in APIs that return these types. Here’s an example that shows how to use some of these basic types:

var express = require("express")
var { createHandler } = require("graphql-http/lib/use/express")
var { buildSchema } = require("graphql")
 
// Construct a schema, using GraphQL schema language
var schema = buildSchema(`
  type Query {
    quoteOfTheDay: String
    random: Float!
    rollThreeDice: [Int]
  }
`)
 
// The root provides a resolver function for each API endpoint
var root = {
  quoteOfTheDay() {
    return Math.random() < 0.5 ? "Take it easy" : "Salvation lies within"
  },
  random() {
    return Math.random()
  },
  rollThreeDice() {
    return [1, 2, 3].map(_ => 1 + Math.floor(Math.random() * 6))
  },
}
 
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")

如果你使用 node server.js 运行此代码并浏览到 http://localhost:4000/graphql,你可以尝试这些 API。

¥If you run this code with node server.js and browse to http://localhost:4000/graphql you can try out these APIs.

这些示例向你展示如何调用返回不同类型的 API。要将不同类型的数据发送到 API,你还需要了解 将参数传递给 GraphQL API

¥These examples show you how to call APIs that return different types. To send different types of data into an API, you will also need to learn about passing arguments to a GraphQL API.