Better way to perform this Relation "transaction" in Prisma

Viewed 169

I posted a question yesterday that has the relevant prisma schema which can be found here.

As a follow up question, when a member creates a new Organization, I'd like for it to become their selected Membership. The only way I've found to do this is to deselect their current Memebership (set it to null), do the create, then restore the relationship if that create didn't work. I have to use updateMany for that initial operation in case there is no selectedMembership. Is that right?

//Deselect the currently selected Org
const updatedMembership = await prisma.membership.updateMany({
    where: {
        selectedById: user.id
    },
    data: {
        selectedById: null
    }
});
if (updatedMembership) {
    //Select the new one.
    const result = await prisma.organization.create({
        data: {
            name: body.name,
            members: {
                create: [{
                    role: MemberRole.OWNER,
                    userId: user.id,
                    selectedById: user.id
                }]
            }
        },
    });
    if (result) {
        res.status(200)
            .json(result);
    } else {
        //Restore the previously selected one if the create failed
        if(user.selectedMembership) {
            await prisma.membership.update({
                where: {
                    id: user.selectedMembership?.id
                },
                data: {
                    selectedById: user.id
                }
            });
        }
        res.status(500).end();
    }
}
1 Answers

You can use the connect API to do all of this in a single query. Just make sure that the user.id is valid.

Here's a much cleaner version of the create and update query logic in your question:

const result = await prisma.organization.create({
        data: {
            name: body.name,
            members: { 
                create: {  
                    role: MemberRole.OWNER,
                    user: {
                        connect: {
                            id: user.id,  // making the user a member of the organization
                        },
                    },
                    selectedBy: {
                        connect: {
                            id: user.id,  // selecting the newly created membership as the user's default organization
                        },
                    },
                },
            },
        },
    });

This will handle all cases, regardless of whether the user with id = user.id currently:

  • Is a member of other organization(s) and has another membership as their default
  • Is a member of other organization(s) but has no default membership
  • Is not a member of any organization and has no default membership
Related