Create a custom Scalar Type for Email Address

6 Sept 2021

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])?)*$/;

const validate = (value) => {
  if (typeof value !== "string") {
    throw new GraphQLError(`Value is not string: ${value}`);
  }

  if (!EMAIL_ADDRESS_REGEX.test(value)) {
    throw new GraphQLError(`Value is not a valid email address: ${value}`);
  }

  return value;
};
const parseLiteral = (ast) => {
  if (ast.kind !== Kind.STRING) {
    throw new GraphQLError(
      `Query error: Can only parse strings as email addresses but got a: ${ast.kind}`
    );
  }

  return validate(ast.value);
};
const GraphQLEmailAddressConfig = {
  name: "EmailAddress",
  description: "A valid email address",
  serialize: validate,
  parseValue: validate,
  parseLiteral,
};

const GraphQLEmailAddress = new GraphQLScalarType(GraphQLEmailAddressConfig);
const typeDefs = `
  scalar EmailAddress
`;

const resolvers = {
  EmailAddress: GraphQLEmailAddress,
};