NoSchemaIntrospectionCustomRule.js.flow 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. // @flow strict
  2. import { GraphQLError } from '../../../error/GraphQLError';
  3. import type { FieldNode } from '../../../language/ast';
  4. import type { ASTVisitor } from '../../../language/visitor';
  5. import { getNamedType } from '../../../type/definition';
  6. import { isIntrospectionType } from '../../../type/introspection';
  7. import type { ValidationContext } from '../../ValidationContext';
  8. /**
  9. * Prohibit introspection queries
  10. *
  11. * A GraphQL document is only valid if all fields selected are not fields that
  12. * return an introspection type.
  13. *
  14. * Note: This rule is optional and is not part of the Validation section of the
  15. * GraphQL Specification. This rule effectively disables introspection, which
  16. * does not reflect best practices and should only be done if absolutely necessary.
  17. */
  18. export function NoSchemaIntrospectionCustomRule(
  19. context: ValidationContext,
  20. ): ASTVisitor {
  21. return {
  22. Field(node: FieldNode) {
  23. const type = getNamedType(context.getType());
  24. if (type && isIntrospectionType(type)) {
  25. context.reportError(
  26. new GraphQLError(
  27. `GraphQL introspection has been disabled, but the requested query contained the field "${node.name.value}".`,
  28. node,
  29. ),
  30. );
  31. }
  32. },
  33. };
  34. }