我正在构建一个 graphql 应用程序,其中User
可以有一堆Entries
。这是一个 n 到 m 的关系,中间表/边保存有关该关系的其他信息。我的 graphql 模式看起来像这样:
type User {
id: ID!,
entries(…): [UserEntry]
}
type UserEntry {
id: ID!,
user: User,
entry: Entry,
someOtherAttribute: String,
yetAnotherAttribute: String
}
type Entry {...}
type Query {
me: User!
userEntry(userEntryId: ID!): UserEntry!
}
我想按照中继游标连接规范向该entries
字段添加游标样式分页。所以我想UserEntry
会变成这样:
type UserEntryEdge {
node: Entry,
cursor: String,
someOtherAttribute: String,
yetAnotherEdgeAttribute: String
}
但是我希望仍然能够直接查询UserEntry
/UserEntryEdge
,在这种情况下,例如cursor
字段将无关紧要。
设计我的 graphql 模式以便能够直接查询边缘数据的最佳方法是什么?
(仅供参考:我在服务器和客户端上使用nodejs和apollo框架套件(
您实际上是在像这样对架构进行建模
[User] hasAndBelongsToMany [Entry]
但你可以这样想
[User] hasMany [UserEntry] hasOne [Entry]
and
[Entry] hasMany [UserEntry] hasOne [User]
所以,回到你的 GraphQL 模式:
type User {
id: ID!,
userEntriesConnection(…): UserEntriesConnection!
}
type UserEntriesConnection {
edges: [UserEntryEdge]!,
pageInfo: ...
}
type UserEntryEdge {
cursor: String!,
node: UserEntry,
}
type UserEntry {
id: ID!,
user: User,
entry: Entry,
someOtherAttribute: String,
yetAnotherAttribute: String
}
type Entry { ... }
type Query {
me: User!
userEntry(userEntryId: ID!): UserEntry!
}
这符合您的需求吗?查询会更详细,因为有更深入,但它更完整。
如果您仍然需要直接查询UserEntry
那么我想您应该将其保留为架构中的单独类型,而不是将其转换为Edge
类型。
所以只要保持UserEntry
和UserEntryEdge
.
生成的架构可能如下所示:
type User {
id: ID!,
entries(…): [UserEntryConnection]
}
type UserEntryConnection {
edges: [UserEntryEdge]
nodes: [Entry] # shortcut (GitHub does like that)
pageInfo: PageInfo!
}
type UserEntryEdge {
node: Entry,
cursor: String,
info: UserEntry # To not duplicate attributes, you can use UserEntry type here
}
type UserEntry {
id: ID!,
user: User,
entry: Foo,
someOtherAttribute: String,
yetAnotherAttribute: String
}
type Entry {...}
type Query {
me: User!
userEntry(userEntryId: ID!): UserEntry! # keep userEntry field as is
}