muhajir
12/18/2018, 6:27 AMtype User {
id: ID! @unique
authorId: String! @unique
name: String!
messages: [Message!]!
}
type Message {
id: ID! @unique
content: String
author: User!
}
Suppose I have this message data in this form
// example message data
{
authorId: 'some-id",
content: "some content"
}
I want to record that message in database. And create new user with that authorId, if it doesn't exist yet.
async function recordMessage(message) {
const userExists = await prisma.$exists.user({
authorId: data.authorId
});
if (!userExists) {
await prisma.createAuthor({
authorId: data.authorId
})
}
prisma.createMessage({
content: data.content,
author: {
connect: {
authorId: data.authorId
}
}
});
}
Sometime one message and another message have same authorId
. That's why I check userExist
first.
But, when I run recordMessage(message), alot of times. Sometime it result in race condition, it says user doesn't exist yet. But when we're creating new author, I got Unique constraint
Error. Which means there's already user with that authorId
right?
How do you guys handle this situation?
Is there any plan in the future for something like this:
prisma.findOrCreateAuthor({
authorId: "some-id"
})
Some ORM have this feature, like http://docs.sequelizejs.com/manual/tutorial/models-usage.html#-findorcreate-search-for-a-specific-element-or-create-it-if-not-available .
Or perhaps, upsert without update
prisma.upsertAuthor({
where: {
authorId: "some-id"
},
create: {
authorId: "some-id"
}
})
I know, it's possible to use upsert. But it requires us to update
the field. Which Is not necassary in this case.
Thanks