I'm trying to implement my own GraphQL backend using NodeJS & Prisma.
For now, I just have 2 simple types:
User:
type User {
id: ID! @unique
email: String!
address: Address! @relation(name:"UserAddress")
}
Address:
type Address {
id: ID! @unique
name: String!
user: User! @relation(name:"UserAddress")
}
And one simple mutation, to create a user, which is resolved by:
async signup(parent, {email}, ctx, info) {
return ctx.db.mutation.createUser({
data: {email},
})
}
But this doesn't work because while creating User, I omit its address. I know I should add an address field in data with the id of this user, but because we are creating it we have no access to it right now. How to fix this? (I want this to be done in the server, if possible by keeping the ! and atomicity otherwise can split into 2 mutations if that's the trick?).
Best.
If you don't plan on always providing an address when creating a new User, I'd suggest you make the address field optional. Otherwise, no matter how many steps you take and how fast you do it, there's always a moment when a potential query would return an error.
TBH, I don't even get why you'd want it to be required. I'm sure you can do without, or, if it's really mandatory, you should rather "force" the user to fill in such details when/after they register. But still, keep it optional in the schema.
If you're asking for address info at signup, the way I see it, there are 2 ways you can go about it. Either way, there would still be a single resolver. And, yeah, you may flag the address field as required
If Address and User are separate entities, still a single resolver, but more steps involved and you can can go about it in 2 ways as well:
You save the user, wait for the response to get the id
, add the user_id
field to the address and save it. After saving the address, you need to update the user by adding the address_id
field.
If you're using mongodb there's absolutely no reason why you shouldn't generate those ids yourself. with new ObjectId()
, add them where needed and then save the user and address. This way you could also return an optimistic response, or just wait for both operations to finish.