apply-id-codec-decorator.ts 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. import { EntityIdStrategy } from '../../config/entity-id-strategy';
  2. import { getConfig } from '../../config/vendure-config';
  3. import { IdCodec } from './id-codec';
  4. export type IdCodecType = { [K in keyof IdCodec]: IdCodec[K] };
  5. /**
  6. * A decorator for use on resolver methods which automatically applies the configured
  7. * EntityIdStrategy to the arguments & return values of the resolver.
  8. *
  9. * @param transformKeys - An optional array of keys of the arguments object to be decoded. If not set,
  10. * then the arguments will be walked recursively and any `id` property will be decoded.
  11. * @param customIdCodec - A custom IdCodec instance, primarily intended for testing.
  12. */
  13. export function ApplyIdCodec(transformKeys?: string[], customIdCodec?: IdCodecType) {
  14. let strategy: EntityIdStrategy;
  15. let idCodec: IdCodecType;
  16. return (target: any, name: string | symbol, descriptor: PropertyDescriptor) => {
  17. if (!customIdCodec) {
  18. strategy = getConfig().entityIdStrategy;
  19. idCodec = new IdCodec(strategy);
  20. } else {
  21. idCodec = customIdCodec;
  22. }
  23. const originalFn = descriptor.value;
  24. if (typeof originalFn === 'function') {
  25. descriptor.value = function(rootValue?: any, args?: any, context?: any, info?: any) {
  26. const encodedArgs = idCodec.decode(args, transformKeys);
  27. const result = originalFn.apply(this, [rootValue, encodedArgs, context, info]);
  28. if (result.then) {
  29. return result.then(data => idCodec.encode(data));
  30. } else {
  31. return idCodec.encode(result);
  32. }
  33. };
  34. }
  35. };
  36. }