1
0

product-review-shop.resolver.ts 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import { Args, Mutation, Resolver } from '@nestjs/graphql';
  2. import {
  3. Ctx,
  4. Customer,
  5. ListQueryBuilder,
  6. Product,
  7. ProductVariant,
  8. RequestContext,
  9. Transaction,
  10. TransactionalConnection,
  11. } from '@vendure/core';
  12. import { ProductReview } from '../entities/product-review.entity';
  13. import { MutationSubmitProductReviewArgs, MutationVoteOnReviewArgs } from '../generated-shop-types';
  14. @Resolver()
  15. export class ProductReviewShopResolver {
  16. constructor(private connection: TransactionalConnection, private listQueryBuilder: ListQueryBuilder) {}
  17. @Transaction()
  18. @Mutation()
  19. async submitProductReview(
  20. @Ctx() ctx: RequestContext,
  21. @Args() { input }: MutationSubmitProductReviewArgs,
  22. ) {
  23. const review = new ProductReview(input);
  24. const product = await this.connection.getEntityOrThrow(ctx, Product, input.productId);
  25. review.product = product;
  26. review.state = 'new';
  27. if (input.variantId) {
  28. const variant = await this.connection.getEntityOrThrow(ctx, ProductVariant, input.variantId);
  29. review.productVariant = variant;
  30. }
  31. if (input.customerId) {
  32. const customer = await this.connection.getEntityOrThrow(ctx, Customer, input.customerId);
  33. review.author = customer;
  34. }
  35. return this.connection.getRepository(ctx, ProductReview).save(review);
  36. }
  37. @Transaction()
  38. @Mutation()
  39. async voteOnReview(@Ctx() ctx: RequestContext, @Args() { id, vote }: MutationVoteOnReviewArgs) {
  40. const review = await this.connection.getEntityOrThrow(ctx, ProductReview, id, {
  41. relations: ['product'],
  42. where: {
  43. state: 'approved',
  44. },
  45. });
  46. if (vote) {
  47. review.upvotes++;
  48. } else {
  49. review.downvotes++;
  50. }
  51. return this.connection.getRepository(ctx, ProductReview).save(review);
  52. }
  53. }