assertValidName.js.flow 898 B

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