graphql-subscriptions-plugin.ts 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import { Args, Mutation, Resolver, Subscription } from '@nestjs/graphql';
  2. import {
  3. Ctx,
  4. ID,
  5. Order,
  6. OrderService,
  7. PluginCommonModule,
  8. RequestContext,
  9. TransactionalConnection,
  10. VendurePlugin,
  11. } from '@vendure/core';
  12. import { PubSub } from 'graphql-subscriptions';
  13. import { gql } from 'graphql-tag';
  14. import { Inject } from '@nestjs/common';
  15. @Resolver()
  16. class OrderStateResolver {
  17. constructor(
  18. @Inject('PUB_SUB') private readonly pubSub: PubSub,
  19. private readonly db: TransactionalConnection,
  20. ) {}
  21. @Subscription(() => Order, {
  22. filter: (payload, variables) => {
  23. return payload.orderStateUpdated.id === variables.orderId;
  24. },
  25. })
  26. async orderStateUpdated(@Args('orderId') orderId: ID) {
  27. return this.pubSub.asyncIterator('orderStateUpdated');
  28. }
  29. @Mutation(() => Order)
  30. async triggerOrderStateUpdated(@Ctx() ctx: RequestContext, @Args('orderId') orderId: ID) {
  31. const order = await this.db.getEntityOrThrow(ctx, Order, orderId);
  32. return this.pubSub.publish('orderStateUpdated', { orderStateUpdated: order });
  33. }
  34. }
  35. @VendurePlugin({
  36. imports: [PluginCommonModule],
  37. shopApiExtensions: {
  38. schema: gql`
  39. extend type Subscription {
  40. orderStateUpdated(orderId: ID!): Order!
  41. }
  42. extend type Mutation {
  43. triggerOrderStateUpdated(orderId: ID!): Order
  44. }
  45. `,
  46. resolvers: [OrderStateResolver],
  47. },
  48. configuration: config => {
  49. return config;
  50. },
  51. })
  52. export class GraphqlSubscriptionsPlugin {}