diff --git a/back-end/src/resolvers/AdResolver.ts b/back-end/src/resolvers/AdResolver.ts index 69e8fac..067c2d4 100644 --- a/back-end/src/resolvers/AdResolver.ts +++ b/back-end/src/resolvers/AdResolver.ts @@ -7,12 +7,22 @@ import { Mutation, Query, Resolver, + createMethodDecorator, } from "type-graphql"; import Ad from "../entities/ad"; import { CreateOrUpdateAd } from "../entities/ad.args"; import { Context } from ".."; import User from "../entities/user"; +export function AdOwner() { + return createMethodDecorator(async ({ args, context }, next) => { + if (await (context as Context).user?.isAdOwner(args.id)) { + return next(); + } + throw new Error("You must own the ad to perform this action."); + }); +} + @Resolver() export class AdResolver { @Query(() => [Ad]) @@ -32,24 +42,19 @@ export class AdResolver { } @Authorized() + @AdOwner() @Mutation(() => Ad) async updateAd( @Arg("id", () => ID) id: string, @Args() args: CreateOrUpdateAd, - @Ctx() { user }: Context, ) { - if (await user?.isAdOwner(id)) { - return Ad.updateAd(id, args); - } - throw new Error("Only the ad owner is allowed to update it."); + return Ad.updateAd(id, args); } @Authorized() + @AdOwner() @Mutation(() => Ad) - async deleteAd(@Arg("id", () => ID) id: string, @Ctx() { user }: Context) { - if (await user?.isAdOwner(id)) { - return Ad.deleteAd(id); - } - throw new Error("Only the ad owner is allowed to delete it."); + async deleteAd(@Arg("id", () => ID) id: string) { + return Ad.deleteAd(id); } }