assertValidName.js.flow 987 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. // @flow strict
  2. import devAssert from '../jsutils/devAssert';
  3. import { GraphQLError } from '../error/GraphQLError';
  4. import { type ASTNode } from '../language/ast';
  5. const NAME_RX = /^[_a-zA-Z][_a-zA-Z0-9]*$/;
  6. /**
  7. * Upholds the spec rules about naming.
  8. */
  9. export function assertValidName(name: string): string {
  10. const error = isValidNameError(name);
  11. if (error) {
  12. throw error;
  13. }
  14. return name;
  15. }
  16. /**
  17. * Returns an Error if a name is invalid.
  18. */
  19. export function isValidNameError(
  20. name: string,
  21. node?: ASTNode | void,
  22. ): GraphQLError | void {
  23. devAssert(typeof name === 'string', 'Expected string');
  24. if (name.length > 1 && name[0] === '_' && name[1] === '_') {
  25. return new GraphQLError(
  26. `Name "${name}" must not begin with "__", which is reserved by GraphQL introspection.`,
  27. node,
  28. );
  29. }
  30. if (!NAME_RX.test(name)) {
  31. return new GraphQLError(
  32. `Names must match /^[_a-zA-Z][_a-zA-Z0-9]*$/ but "${name}" does not.`,
  33. node,
  34. );
  35. }
  36. }