ScalarLeafsRule.mjs 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. import { inspect } from '../../jsutils/inspect.mjs';
  2. import { GraphQLError } from '../../error/GraphQLError.mjs';
  3. import { getNamedType, isLeafType } from '../../type/definition.mjs';
  4. /**
  5. * Scalar leafs
  6. *
  7. * A GraphQL document is valid only if all leaf fields (fields without
  8. * sub selections) are of scalar or enum types.
  9. */
  10. export function ScalarLeafsRule(context) {
  11. return {
  12. Field(node) {
  13. const type = context.getType();
  14. const selectionSet = node.selectionSet;
  15. if (type) {
  16. if (isLeafType(getNamedType(type))) {
  17. if (selectionSet) {
  18. const fieldName = node.name.value;
  19. const typeStr = inspect(type);
  20. context.reportError(
  21. new GraphQLError(
  22. `Field "${fieldName}" must not have a selection since type "${typeStr}" has no subfields.`,
  23. {
  24. nodes: selectionSet,
  25. },
  26. ),
  27. );
  28. }
  29. } else if (!selectionSet) {
  30. const fieldName = node.name.value;
  31. const typeStr = inspect(type);
  32. context.reportError(
  33. new GraphQLError(
  34. `Field "${fieldName}" of type "${typeStr}" must have a selection of subfields. Did you mean "${fieldName} { ... }"?`,
  35. {
  36. nodes: node,
  37. },
  38. ),
  39. );
  40. }
  41. }
  42. },
  43. };
  44. }