Ale*_*ini 5 graphql react-apollo graphcool apollo-client
嗨,我试图在我的https://www.graph.cool/ db 上写一个带有变异的数据.我的项目是一个React web-app,我使用Apollo作为graphql客户端和graphql-tag npm包作为模板文字解析器.
问题是我不知道如何使用嵌套数据为正确的变异安排gql模板字符串.我的架构看起来像这样,例如,注意"公司"类型的字段"地址"是"地址"对象类型的数组.
type Company {
name: String!
website: String
Owner: User
Addresses: [Addresses]
}
type User {
name: String!
email: String
}
type Address {
street: String!
city: String!
country: String
contacts: [Contact]
}
type Contact {
name: String
email: String
phone: String
}
Run Code Online (Sandbox Code Playgroud)
例如,我想在一个突变中同时创建一个新公司,它的新所有者和多个地址.对于我需要创建新联系人的地址.
mar*_*ani 14
您可以使用我们所谓的嵌套突变来实现这一目标.首先,让我们看看我们如何从GraphiQL游乐场做到这一点:
mutation createNestedCompany {
createCompany(
owner: {
name: "Mickey"
email: "mickey@mouse.com"
}
addresses: [{
street: "A street"
city: "A city"
country: "A country"
contacts: [{
name: "Mickey"
email: "mickey@mouse.com"
phone: "+1 23456789"
}]
}, {
street: "B street"
city: "B city"
country: "B country"
contacts: [{
name: "Minney"
email: "minney@mouse.com"
phone: "+9 87654321"
}]
}]
) {
id
owner {
id
}
addresses {
id
contacts {
id
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,该createCompany
变异具有object参数owner
和list对象参数addresses
.addresses
有一个嵌套的contacts
列表对象参数.
使用Apollo Client,我们使用GraphQL变量指定输入参数,所以让我们看看它在这种情况下的外观:
const createNestedCompany = gql`
mutation createNestedCompany(
$owner: CompanyownerUser
$addresses: [CompanyaddressesAddress!]
) {
createCompany(
owner: $owner
addresses: $addresses
) {
id
owner {
id
}
addresses {
id
contacts {
id
}
}
}
}
`
Run Code Online (Sandbox Code Playgroud)
当用Apollo调用变异时,我们现在必须将变量指定为对象:
const variables = {
owner: {
name: "Mickey"
email: "mickey@mouse.com"
},
addresses: [{
street: "A street"
city: "A city"
country: "A country"
contacts: [{
name: "Mickey"
email: "mickey@mouse.com"
phone: "+1 23456789"
}]
}, {
street: "A street"
city: "A city"
country: "A country"
contacts: [{
name: "Minney"
email: "minney@mouse.com"
phone: "+9 87654321"
}]
}]
}
Run Code Online (Sandbox Code Playgroud)
并使用变量调用变异:
this.props.createNestedCompany({ variables })
.then((response) => {
console.log('Company, owner and addresses plus contacts created');
}).catch((e) => {
console.error(e)
})
Run Code Online (Sandbox Code Playgroud)
变量类型CompanyownerUser
和[CompanyaddressesAddress!]
取决于的组合的多样性(以酮;对多),该相关模型(Company
和User
; Company
和Address
)和相关领域(owner
; addresses
).导航到createCompany
变异时,可以在GraphiQL playground文档中找到所有类型名称.
归档时间: |
|
查看次数: |
1520 次 |
最近记录: |