我的架构如下:
type Artist @model {
id: ID! @isUnique
createdAt: DateTime!
updatedAt: DateTime!
name: String! @isUnique
songkickId: String
shows: [Show!]! @relation(name: "ArtistShow")
}
type Show @model {
id: ID! @isUnique
createdAt: DateTime!
updatedAt: DateTime!
name: String
songkickId: String
date: DateTime!
soldOut: Boolean!
pit: Boolean!
ages: String!
price: String!
multiDay: Boolean!
artists: [Artist!]! @relation(name: "ArtistShow")
venue: Venue! @relation(name: "ShowVenue")
}
type Venue @model {
id: ID! @isUnique
createdAt: DateTime!
updatedAt: DateTime!
name: String! @isUnique
address: String
latitude: Float
longitude: Float
metro: String
songkickId: String @isUnique
shows: [Show!]! @relation(name: "ShowVenue")
}
我写了一些突变,给定JSON数据,创建Artist
和Venue
并将其返回给我。
在我想要创建Show
时,我有:
Artist
ID Venue
Show
数据的所有必填信息(在名为showInfo
的对象中)我的突变看起来像这样:
mutation: gql`
mutation {
createShow(
date: "${showInfo.date}"
soldOut: ${showInfo.soldOut}
pit: ${showInfo.pit}
ages: "${showInfo.ages}"
price: "${showInfo.price}"
multiDay: ${showInfo.multiDay}
) {
id
}
}
`,
如何编辑此内容,以便在我创建的Show
与相应的Venue
和Artist
ID之间创建关系?
答案 0 :(得分:0)
我必须构建JSON,以便在我编写Artist
时可以访问Venue
和Show
的列表。
然后,我必须将每个Artist
和Venue
(或验证这些是否已经写入)写入graphcool并获取相应的ID。
然后我执行了如下函数:
async findShowOrCreate (showInfo, artists, venue) {
const tempDate = new Date(showInfo.date);
this.logger.info(`BEGIN : write show to graphcool (${showInfo.venue} on ${tempDate.toDateString()})`);
const showQuery = `
query ($venueId: ID!, $date: DateTime) {
allShows(filter: {
venue: {
id: $venueId
}
date: $date
}) {
id
}
}
`
const existentialShowTest = await this.client.request(showQuery,
{venueId: venue, date: showInfo.date})
if (existentialShowTest.allShows.length < 1){
const addShowQuery = `
mutation createShow($artistsIds:[ID!], $venueId:ID ) {
createShow (
artistsIds: $artistsIds
venueId: $venueId
date: "${showInfo.date}"
soldOut: ${showInfo.soldOut}
pit: ${showInfo.pit}
ages: "${showInfo.ages}"
price: "${showInfo.price}"
multiDay: ${showInfo.multiDay}
) {
id
}
}
`
const finalResult = await this.client.request(addShowQuery,
{venueId: venue, artistsIds: artists})
.then(data => {
const result = data.createShow.id
this.logger.info(`FINISH: write show to graphcool as ${result}`)
return result
})
.catch(error => this.logger.error(error));
return finalResult
} else {
this.logger.info(`FINISH: found show in graphcool`)
return existentialShowTest.allShows[0]
}
}
首先运行查询以确保表示特定日期和Show
的并集的Venue
在graphcool中已经存在,然后运行变异以添加{{ 1}}。
请注意,此突变的具体结构是为现有的Show
和Venue
对象(后者以列表形式)接收ID并将这些作为变量附加到行中:
Artist
使用 client.request(addShowQuery,
{venueId: venue, artistsIds: artists})
库,它允许您将变量的哈希值传递给graphcool的请求。