event-bus-transactions-plugin.ts 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. /* eslint-disable @typescript-eslint/no-non-null-assertion */
  2. import { OnModuleInit } from '@nestjs/common';
  3. import { Args, Mutation, Resolver } from '@nestjs/graphql';
  4. import {
  5. Asset,
  6. AssetEvent,
  7. AssetService,
  8. Ctx,
  9. EventBus,
  10. ID,
  11. Logger,
  12. PluginCommonModule,
  13. RequestContext,
  14. Transaction,
  15. TransactionalConnection,
  16. VendurePlugin,
  17. } from '@vendure/core';
  18. import gql from 'graphql-tag';
  19. @Resolver()
  20. class TestResolver {
  21. constructor(private assetService: AssetService) {}
  22. @Transaction()
  23. @Mutation()
  24. async setAssetName(@Ctx() ctx: RequestContext, @Args() args: { id: ID; name: string }) {
  25. await this.assetService.update(ctx, {
  26. id: args.id,
  27. name: args.name,
  28. });
  29. await new Promise(resolve => setTimeout(resolve, 500));
  30. Logger.info('setAssetName returning');
  31. return true;
  32. }
  33. }
  34. // A plugin to explore solutions to https://github.com/vendurehq/vendure/issues/1107
  35. @VendurePlugin({
  36. imports: [PluginCommonModule],
  37. adminApiExtensions: {
  38. schema: gql`
  39. extend type Mutation {
  40. setAssetName(id: ID!, name: String!): Boolean
  41. }
  42. `,
  43. resolvers: [TestResolver],
  44. },
  45. })
  46. export class EventBusTransactionsPlugin implements OnModuleInit {
  47. constructor(
  48. private eventBus: EventBus,
  49. private connection: TransactionalConnection,
  50. ) {}
  51. onModuleInit(): any {
  52. this.eventBus.ofType(AssetEvent).subscribe(async event => {
  53. Logger.info('Event handler started');
  54. const repository = this.connection.getRepository(event.ctx, Asset);
  55. await new Promise(resolve => setTimeout(resolve, 1000));
  56. const asset = await repository.findOne(event.asset.id);
  57. Logger.info(`The asset name is ${asset?.name as string}`);
  58. asset!.name = asset!.name + ' modified';
  59. await repository.save(asset!);
  60. });
  61. }
  62. }