NoSchemaIntrospectionCustomRule.mjs 1.0 KB

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