End to End React with Prisma 2
Start at the beginning and work your way through this project. The code for each step as well as the finished project can be found in the Github repository.
14. Add Delete mutations
Objective: Add all of the delete mutations we will need.
In this step we will add delete mutations for feeds, bundles, and savedArticles. Let's start by adding the following resolver functions:
utils/api/resolvers.ts
ts
// other imports and definitionsexport const resolvers = {// other resolver definitionsMutation: {// other mutationsdeleteBundle: async (parent, { data: { id } }, { prisma, user }) => {const bundle = await prisma.bundle.findOne({ where: { id }, include: { author: true, likes: true } });await verifyOwnership(bundle, user);await prisma.bundle.delete({ where: { id: bundle.id } });return bundle;},deleteFeed: async (parent, { data: { id } }, { prisma, user }) => {const feed = await prisma.feed.findOne({ where: { id }, include: { author: true, likes: true } });await verifyOwnership(feed, user);await prisma.feed.delete({ where: { id: feed.id } });return feed;},deleteSavedArticle: async (parent, { data: { id } }, { prisma, user }) => {const savedArticle = await prisma.savedArticle.findOne({ where: { id }, include: { author: true } });await verifyOwnership(savedArticle, user);return prisma.savedArticle.delete({ where: { id: savedArticle.id } });},}
Just like before, we want to always look up the item in question first and confirm that the owner of that item matches the owner trying to perform the delete operation. Next, let's add these mutations to the type definitions file. Note that although we can look up bundles and feeds by their id
s, we can only look up savedArticles by their url
. When it comes to deleting feeds, bundles, and savedArticles though, we use an id
in all cases.
utils/api/typeDefs.ts
ts
# other type defsinput DeleteSavedArticleInput {id: String}# other type defstype Mutation {deleteBundle(data: BundleInput): BundledeleteFeed(data: FeedInput): FeeddeleteSavedArticle(data: DeleteSavedArticleInput): SavedArticle}
And with that, we have built our backend! The only thing left is to reset our database by calling the mutation { resetAll }
mutation and to revert our context so that it will be ready for properly setting the user from the frontend. Restore the context function to look like this:
utils/api/context.ts
ts
export const context = async ({ req }) => {try {const { user: auth0User } = await auth0.getSession(req)let user = await prisma.user.findOne({ where: { auth0: auth0User.sub } })if (!user) {const { picture, nickname, sub } = auth0Useruser = await prisma.user.create({data: { id: uuidv4(), auth0: sub, nickname, picture },})}return { user, prisma }} catch (e) {return { user: {}, prisma }}}