customer-avatar.resolver.ts 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import { Args, Mutation, Resolver } from '@nestjs/graphql';
  2. import { Asset } from '@vendure/common/lib/generated-types';
  3. import {
  4. Allow,
  5. AssetService,
  6. Ctx,
  7. CustomerService,
  8. isGraphQlErrorResult,
  9. Permission,
  10. RequestContext,
  11. Transaction,
  12. } from '@vendure/core';
  13. @Resolver()
  14. export class CustomerAvatarResolver {
  15. constructor(private assetService: AssetService, private customerService: CustomerService) {}
  16. @Transaction()
  17. @Mutation()
  18. @Allow(Permission.Authenticated)
  19. async setCustomerAvatar(
  20. @Ctx() ctx: RequestContext,
  21. @Args() args: { file: any },
  22. ): Promise<Asset | undefined> {
  23. const userId = ctx.activeUserId;
  24. if (!userId) {
  25. return;
  26. }
  27. const customer = await this.customerService.findOneByUserId(ctx, userId);
  28. if (!customer) {
  29. return;
  30. }
  31. // Create an Asset from the uploaded file
  32. const asset = await this.assetService.create(ctx, {
  33. file: args.file,
  34. tags: ['avatar'],
  35. });
  36. // Check to make sure there was no error when
  37. // creating the Asset
  38. if (isGraphQlErrorResult(asset)) {
  39. // MimeTypeError
  40. throw asset;
  41. }
  42. // Asset created correctly, so assign it as the
  43. // avatar of the current Customer
  44. await this.customerService.update(ctx, {
  45. id: customer.id,
  46. customFields: {
  47. avatarId: asset.id,
  48. },
  49. });
  50. return asset;
  51. }
  52. }