[ PROMPT_NODE_23654 ]
graphql-schema-design
[ SKILL_DOCUMENTATION ]
# GraphQL 模式设计模式
## 模式组织
### 模块化模式结构
graphql
# user.graphql
type User {
id: ID!
email: String!
name: String!
posts: [Post!]!
}
extend type Query {
user(id: ID!): User
users(first: Int, after: String): UserConnection!
}
extend type Mutation {
createUser(input: CreateUserInput!): CreateUserPayload!
}
# post.graphql
type Post {
id: ID!
title: String!
content: String!
author: User!
}
extend type Query {
post(id: ID!): Post
}
## 类型设计模式
### 1. 非空类型 (Non-Null Types)
graphql
type User {
id: ID! # 始终必填
email: String! # 必填
phone: String # 可选 (可为空)
posts: [Post!]! # 非空数组,且包含非空对象
tags: [String!] # 可为空数组,包含非空字符串
}
### 2. 用于多态的接口 (Interfaces)
graphql
interface Node {
id: ID!
createdAt: DateTime!
}
type User implements Node {
id: ID!
createdAt: DateTime!
email: String!
}
type Post implements Node {
id: ID!
createdAt: DateTime!
title: String!
}
type Query {
node(id: ID!): Node
}
### 3. 用于异构结果的联合类型 (Unions)
graphql
union SearchResult = User | Post | Comment
type Query {
search(query: String!): [SearchResult!]!
}
# 查询示例
{
search(query: "graphql") {
... on User {
name
email
}
... on Post {
title
content
}
... on Comment {
text
author {
name
}
}
}
}
### 4. 输入类型 (Input Types)
graphql
input CreateUserInput {
email: String!
name: String!
password: String!
profileInput: ProfileInput
}
input ProfileInput {
bio: String
avatar: String
website: String
}
input UpdateUserInput {
id: ID!
email: String
name: String
profileInput: ProfileInput
}
## 分页模式
### Relay 光标分页 (推荐)
graphql
type UserConnection {
edges: [UserEdge!]!
pageInfo: PageInfo!
totalCount: Int!
}
type UserEdge {
node: User!
cursor: String!
}
type PageInfo {
hasNextPage: Boolean!
hasPreviousPage: Boolean!
startCursor: String
endCursor: String
}
type Query {
users(first: Int, after: String, last: Int, before: String): UserConnection!
}
# 用法
{
users(first: 10, after: "cursor123") {
edges {
cursor
node {
id
name
}
}
pageInfo {
hasNextPage
endCursor
}
}
}
### 偏移分页 (更简单)
graphql
type UserList {
items: [User!]!
total: I