Pitakun
01/20/2021, 3:20 PMnikolasburk
deleteMany
š you can read more about using it in the docs here.nikolasburk
Pitakun
01/20/2021, 3:31 PMnikolasburk
feels weird to use that syntax when we have an id and another paramCan you elaborate a bit on this use case? Why do you add another param if you already have an ID? (Since the ID already uniquely identifies a record, in my understanding there shouldn't be a need to add another param, but maybe I'm missing something? š)
Pitakun
01/20/2021, 3:36 PMnikolasburk
Pitakun
01/20/2021, 3:45 PM///schema.prisma
model Link {
id Int @id @default(autoincrement())
createdAt DateTime @default(now())
description String
url String
postedBy User? @relation(fields: [postedById], references: [id])
postedById Int?
}
model User {
id Int @id @default(autoincrement())
name String
email String @unique
password String
links Link[]
}
///schema.graphql
type Mutation {
post(url: String!, description: String!): Link!
updateLink(id: ID!, url: String, description: String): Link
deleteLink(id: ID!): Link
signup(email: String!, password: String!, name: String!): AuthPayload
login(email: String!, password: String!): AuthPayload
}
///Mutation.js
updateLink = async (parent, args, context, info) => {
const { userId } = context
const link = await context.prisma.link.findFirst({ where: { AND: [{ id: Number(args.id) }, { postedBy: { id: userId } }] } })
if (!link) {
throw new Error('Cannot find link')
}
return await context.prisma.link.update({
where: { id: Number(args.id) },
data: {
url: args.url || link.url,
description: args.description || link.description
}
})
}
I think this code works for both questions. To clarify:
⢠I just want the same user to be able to delete the Linknikolasburk
updateLink
resolver but you're referring to deleting a link?nikolasburk
Pitakun
01/21/2021, 8:51 AMPitakun
01/21/2021, 8:52 AMdeleteLink = async (parent, args, context, info) => {
const { userId } = context
const link = await context.prisma.link.findFirst({ where: { AND: [{ id: Number(args.id) }, { postedBy: { id: userId } }] } })
if (!link) {
throw new Error('Cannot find link')
}
return await context.prisma.link.delete({ where: { id: Number(args.id) } })
}
nikolasburk
deleteLink = async (parent, args, context, info) => {
const { userId } = context;
const link = await context.prisma.link.findUnique({
where: { id: Number(args.id) },
});
if (!link) {
throw new Error("Cannot find link");
}
if (link.postedById !== userId) {
throw new Error("Only the user who created a link can delete it.");
}
return await context.prisma.link.delete({ where: { id: Number(args.id) } });
};
nikolasburk
findUnique
instead of findFirst
šPitakun
01/21/2021, 11:09 AM