custom-active-order-plugin.ts 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import {
  2. ActiveOrderStrategy,
  3. idsAreEqual,
  4. Injector,
  5. Order,
  6. OrderService,
  7. RequestContext,
  8. TransactionalConnection,
  9. VendurePlugin,
  10. } from '@vendure/core';
  11. import { CustomOrderFields } from '@vendure/core/dist/entity/custom-entity-fields';
  12. import gql from 'graphql-tag';
  13. declare module '@vendure/core/dist/entity/custom-entity-fields' {
  14. interface CustomOrderFields {
  15. orderToken: string;
  16. }
  17. }
  18. class TokenActiveOrderStrategy implements ActiveOrderStrategy {
  19. readonly name = 'orderToken';
  20. private connection: TransactionalConnection;
  21. private orderService: OrderService;
  22. init(injector: Injector) {
  23. this.connection = injector.get(TransactionalConnection);
  24. this.orderService = injector.get(OrderService);
  25. }
  26. defineInputType = () => gql`
  27. input CustomActiveOrderInput {
  28. orderToken: String
  29. }
  30. `;
  31. async determineActiveOrder(ctx: RequestContext, input: { orderToken: string }) {
  32. const qb = this.connection
  33. .getRepository(ctx, Order)
  34. .createQueryBuilder('order')
  35. .leftJoinAndSelect('order.customer', 'customer')
  36. .where('order.customFields.orderToken = :orderToken', { orderToken: input.orderToken });
  37. const order = await qb.getOne();
  38. if (!order) {
  39. return;
  40. }
  41. return order;
  42. // const orderUserId = order.customer && order.customer.user && order.customer.user.id;
  43. // if (idsAreEqual(ctx.activeUserId, orderUserId)) {
  44. // return order;
  45. // } else {
  46. // return;
  47. // }
  48. }
  49. // async createActiveOrder(ctx: RequestContext) {
  50. // const order = await this.orderService.create(ctx, ctx.activeUserId);
  51. // order.customFields.orderToken = Math.random().toString(36).substr(5);
  52. // await this.connection.getRepository(ctx, Order).save(order);
  53. // return order;
  54. // }
  55. }
  56. @VendurePlugin({
  57. configuration: config => {
  58. config.customFields.Order.push({
  59. name: 'orderToken',
  60. type: 'string',
  61. internal: true,
  62. });
  63. config.orderOptions.activeOrderStrategy = new TokenActiveOrderStrategy();
  64. return config;
  65. },
  66. })
  67. export class CustomActiveOrderPlugin {}