digital-fulfillment-handler.ts 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import { FulfillmentHandler, LanguageCode, OrderLine, TransactionalConnection } from '@vendure/core';
  2. import { In } from 'typeorm';
  3. let connection: TransactionalConnection;
  4. /**
  5. * @description
  6. * This is a fulfillment handler for digital products which generates a download url
  7. * for each digital product in the order.
  8. */
  9. export const digitalFulfillmentHandler = new FulfillmentHandler({
  10. code: 'digital-fulfillment',
  11. description: [
  12. {
  13. languageCode: LanguageCode.en,
  14. value: 'Generates product keys for the digital download',
  15. },
  16. ],
  17. args: {},
  18. init: injector => {
  19. connection = injector.get(TransactionalConnection);
  20. },
  21. createFulfillment: async (ctx, orders, lines) => {
  22. const digitalDownloadUrls: string[] = [];
  23. const orderLines = await connection.getRepository(ctx, OrderLine).find({
  24. where: {
  25. id: In(lines.map(l => l.orderLineId)),
  26. },
  27. relations: {
  28. productVariant: true,
  29. },
  30. });
  31. for (const orderLine of orderLines) {
  32. if (orderLine.productVariant.customFields.isDigital) {
  33. // This is a digital product, so generate a download url
  34. const downloadUrl = await generateDownloadUrl(orderLine);
  35. digitalDownloadUrls.push(downloadUrl);
  36. }
  37. }
  38. return {
  39. method: 'Digital Fulfillment',
  40. trackingCode: 'DIGITAL',
  41. customFields: {
  42. downloadUrls: digitalDownloadUrls,
  43. },
  44. };
  45. },
  46. });
  47. function generateDownloadUrl(orderLine: OrderLine) {
  48. // This is a dummy function that would generate a download url for the given OrderLine
  49. // by interfacing with some external system that manages access to the digital product.
  50. // In this example, we just generate a random string.
  51. const downloadUrl = `https://example.com/download?key=${Math.random().toString(36).substring(7)}`;
  52. return Promise.resolve(downloadUrl);
  53. }