1
0

slow-mutation-plugin.ts 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. import { Args, Mutation, Resolver } from '@nestjs/graphql';
  2. import {
  3. Asset,
  4. AssetType,
  5. Country,
  6. Ctx,
  7. PluginCommonModule,
  8. Product,
  9. ProductAsset,
  10. RequestContext,
  11. Transaction,
  12. TransactionalConnection,
  13. VendurePlugin,
  14. } from '@vendure/core';
  15. import gql from 'graphql-tag';
  16. @Resolver()
  17. export class SlowMutationResolver {
  18. constructor(private connection: TransactionalConnection) {}
  19. /**
  20. * A mutation which simulates some slow DB operations occurring within a transaction.
  21. */
  22. @Transaction()
  23. @Mutation()
  24. async slowMutation(@Ctx() ctx: RequestContext, @Args() args: { delay: number }) {
  25. const delay = Math.round(args.delay / 2);
  26. const country = await this.connection.getRepository(ctx, Country).findOneOrFail({
  27. where: {
  28. code: 'AT',
  29. },
  30. });
  31. country.enabled = false;
  32. await new Promise(resolve => setTimeout(resolve, delay));
  33. await this.connection.getRepository(ctx, Country).save(country);
  34. country.enabled = true;
  35. await new Promise(resolve => setTimeout(resolve, delay));
  36. await this.connection.getRepository(ctx, Country).save(country);
  37. return true;
  38. }
  39. /**
  40. * This mutation attempts to cause a deadlock
  41. */
  42. @Transaction()
  43. @Mutation()
  44. async attemptDeadlock(@Ctx() ctx: RequestContext) {
  45. const product = await this.connection.getRepository(ctx, Product).findOneOrFail({ where: { id: 1 } });
  46. const asset = await this.connection.getRepository(ctx, Asset).save(
  47. new Asset({
  48. name: 'test',
  49. type: AssetType.BINARY,
  50. mimeType: 'test/test',
  51. fileSize: 1,
  52. source: '',
  53. preview: '',
  54. }),
  55. );
  56. await new Promise(resolve => setTimeout(resolve, 100));
  57. const productAsset = await this.connection.getRepository(ctx, ProductAsset).save(
  58. new ProductAsset({
  59. assetId: asset.id,
  60. productId: product.id,
  61. position: 0,
  62. }),
  63. );
  64. await this.connection.getRepository(ctx, Product).update(product.id, { enabled: false });
  65. return true;
  66. }
  67. }
  68. @VendurePlugin({
  69. imports: [PluginCommonModule],
  70. adminApiExtensions: {
  71. resolvers: [SlowMutationResolver],
  72. schema: gql`
  73. extend type Mutation {
  74. slowMutation(delay: Int!): Boolean!
  75. attemptDeadlock: Boolean!
  76. }
  77. `,
  78. },
  79. })
  80. export class SlowMutationPlugin {}