subscribers.ts 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. import { EntitySubscriberInterface, EventSubscriber } from 'typeorm';
  2. import { CALCULATED_PROPERTIES } from '../common/calculated-decorator';
  3. import { ProductVariantSubscriber } from './product-variant/product-variant.subscriber';
  4. @EventSubscriber()
  5. export class CalculatedPropertySubscriber implements EntitySubscriberInterface {
  6. /**
  7. * For any entity properties decorated with @Calculated(), this subscriber transfers
  8. * the getter from the entity prototype to the entity instance, so that it can be
  9. * correctly enumerated and serialized in the API response.
  10. */
  11. afterLoad(event: any) {
  12. const prototype = Object.getPrototypeOf(event);
  13. if (prototype.hasOwnProperty(CALCULATED_PROPERTIES)) {
  14. for (const property of prototype[CALCULATED_PROPERTIES]) {
  15. const getterDescriptor = Object.getOwnPropertyDescriptor(prototype, property);
  16. const getFn = getterDescriptor && getterDescriptor.get;
  17. if (getFn) {
  18. const boundGetFn = getFn.bind(event);
  19. Object.defineProperties(event, {
  20. [property]: {
  21. get: () => boundGetFn(),
  22. enumerable: true,
  23. },
  24. });
  25. }
  26. }
  27. }
  28. }
  29. }
  30. /**
  31. * A map of the core TypeORM Subscribers.
  32. */
  33. export const coreSubscribersMap = {
  34. ProductVariantSubscriber,
  35. CalculatedPropertySubscriber,
  36. };