LoneSchemaDefinitionRule.js.flow 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. // @flow strict
  2. import { GraphQLError } from '../../error/GraphQLError';
  3. import type { ASTVisitor } from '../../language/visitor';
  4. import type { SDLValidationContext } from '../ValidationContext';
  5. /**
  6. * Lone Schema definition
  7. *
  8. * A GraphQL document is only valid if it contains only one schema definition.
  9. */
  10. export function LoneSchemaDefinitionRule(
  11. context: SDLValidationContext,
  12. ): ASTVisitor {
  13. const oldSchema = context.getSchema();
  14. const alreadyDefined =
  15. oldSchema?.astNode ??
  16. oldSchema?.getQueryType() ??
  17. oldSchema?.getMutationType() ??
  18. oldSchema?.getSubscriptionType();
  19. let schemaDefinitionsCount = 0;
  20. return {
  21. SchemaDefinition(node) {
  22. if (alreadyDefined) {
  23. context.reportError(
  24. new GraphQLError(
  25. 'Cannot define a new schema within a schema extension.',
  26. node,
  27. ),
  28. );
  29. return;
  30. }
  31. if (schemaDefinitionsCount > 0) {
  32. context.reportError(
  33. new GraphQLError('Must provide only one schema definition.', node),
  34. );
  35. }
  36. ++schemaDefinitionsCount;
  37. },
  38. };
  39. }