/src/scalars/EmailAddress.ts

https://github.com/Urigo/graphql-scalars · TypeScript · 36 lines · 26 code · 10 blank · 0 comment · 5 complexity · 8cfcd417bfb9e8e85c4eb41c37d3f09b MD5 · raw file

  1. import { Kind, GraphQLError, GraphQLScalarType } from 'graphql';
  2. const validate = (value: any) => {
  3. const EMAIL_ADDRESS_REGEX = /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
  4. if (typeof value !== 'string') {
  5. throw new TypeError(`Value is not string: ${value}`);
  6. }
  7. if (!EMAIL_ADDRESS_REGEX.test(value)) {
  8. throw new TypeError(`Value is not a valid email address: ${value}`);
  9. }
  10. return value;
  11. };
  12. export const GraphQLEmailAddress = /*#__PURE__*/ new GraphQLScalarType({
  13. name: 'EmailAddress',
  14. description:
  15. 'A field whose value conforms to the standard internet email address format as specified in RFC822: https://www.w3.org/Protocols/rfc822/.',
  16. serialize: validate,
  17. parseValue: validate,
  18. parseLiteral(ast) {
  19. if (ast.kind !== Kind.STRING) {
  20. throw new GraphQLError(
  21. `Can only validate strings as email addresses but got a: ${ast.kind}`,
  22. );
  23. }
  24. return validate(ast.value);
  25. },
  26. });