slow-mutation-plugin.ts 2.6 KB

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