LoneSchemaDefinition.js.flow 1.3 KB

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