【问题标题】:GraphQL API - mutations of nested objectsGraphQL API - 嵌套对象的突变
【发布时间】:2020-04-05 23:52:36
【问题描述】:

假设我有两种通过 GraphQL API 管理的类型:


type Parent {
    id: ID
    name: String
    children: [Child!]  
}

type Child {
    id: ID
    name: String
}

query {
    parents(): Parent
}

mutations {
    addParent(in: ParentInput!): Parent!
    addChild(parentID: ID!, in: ChildInput!): Child!
    updateChild(childID:ID!, in: ChildInput!): Child!
}

现在,我想知道哪些参数应该接受updateChild。 在上面的示例中,唯一的childID 是必需的。您认为对提供parentID 的用户也提出要求是否可以接受?

updateChild(childID:ID!, parentID: ID!, in: ChildInput)

【问题讨论】:

    标签: graphql api-design


    【解决方案1】:

    我正在使用来自here 的建议,每个突变只有一个输入对象参数,它整合所有必要的字段,而不是将这些字段扁平化为许多不同的输入参数。此外,我倾向于为每个突变设置一个输入对象(Github 突变 API 也使用这种设计风格)

    所以对于 updateChild 突变,我将有以下输入类型:

    mutations {
        updateChild(input: UpdateChildInput): Child
    } 
    
    input UpdateChildInput {
        childId : ID!
        parentId: ID
        name:String 
    }
    

    UpdateChildInput 中包含哪些字段取决于您的 API 要求。包括您的 API 需要支持的字段。因此,如果您的 API 允许用户更改 child 的 parent,您必须将其包含在输入中。

    请注意 parentID 和 name 是可选的,这意味着如果用户不指定它们,它们将不会被更新。

    【讨论】:

      猜你喜欢
      • 2021-05-08
      • 2019-08-24
      • 2020-04-24
      • 2018-08-24
      • 2021-04-09
      • 2018-01-02
      • 2017-07-28
      • 2019-04-10
      相关资源
      最近更新 更多