建模中继光标连接

时间:2017-05-27 14:13:15

标签: graphql relay

我正在构建一个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!
}

我想在Relay Cursor Connections Specification后面的entries字段添加光标样式分页。 所以我猜UserEntry会变成这样:

type UserEntryEdge {
    node: Entry,
    cursor: String,
    someOtherAttribute: String,
    yetAnotherEdgeAttribute: String
}

但我希望仍然可以直接查询UserEntry / UserEntryEdge,在这种情况下,cursor字段可能无关紧要。

设计我的graphql架构以便能够直接查询边缘数据的最佳方法是什么?

(仅供参考:我在服务器和客户端都使用nodejs和apollo框架套件)

2 个答案:

答案 0 :(得分:1)

您实际上正在为此架构建模

[User] hasAndBelongsToMany [Entry]

但你可以考虑像

[User] hasMany [UserEntry] hasOne [Entry]
    and
[Entry] hasMany [UserEntry] hasOne [User]

所以,回到GraphQL Schema:

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!
}

这符合您的需求吗?查询会更冗长,因为有更多深度,但它更完整。

答案 1 :(得分:0)

如果您仍然需要直接查询UserEntry,那么我猜您应该将其作为模式中的单独类型保留,而不是将其转换为Edge类型。

所以请保持UserEntryUserEntryEdge

结果架构可能如下所示:

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
}