get-custom-fields-config-without-interfaces.ts 1.6 KB

123456789101112131415161718192021222324252627282930313233343536
  1. import { GraphQLSchema, isInterfaceType } from 'graphql';
  2. import { CustomFieldConfig, CustomFields } from '../../config/custom-field/custom-field-types';
  3. /**
  4. * @description
  5. * Because the "Region" entity is an interface, it cannot be extended directly, so we need to
  6. * replace it if found in the custom field config with its concrete implementations.
  7. *
  8. * Same goes for the "StockMovement" entity.
  9. */
  10. export function getCustomFieldsConfigWithoutInterfaces(
  11. customFieldConfig: CustomFields,
  12. schema: GraphQLSchema,
  13. ): Array<[entityName: string, config: CustomFieldConfig[]]> {
  14. const entries = Object.entries(customFieldConfig);
  15. const interfaceEntities = ['Region', 'StockMovement'];
  16. for (const entityName of interfaceEntities) {
  17. const index = entries.findIndex(([name]) => name === entityName);
  18. if (index !== -1) {
  19. // An interface type such as Region or StockMovement cannot directly be extended.
  20. // Instead, we will use the concrete types that implement it.
  21. const interfaceType = schema.getType(entityName);
  22. if (isInterfaceType(interfaceType)) {
  23. const implementations = schema.getImplementations(interfaceType);
  24. // Remove the interface from the list of entities to which custom fields can be added
  25. entries.splice(index, 1);
  26. for (const implementation of implementations.objects) {
  27. entries.push([implementation.name, customFieldConfig[entityName] ?? []]);
  28. }
  29. }
  30. }
  31. }
  32. return entries;
  33. }