Create a custom Scalar Type for Email Address

We'll create a custom GraphQL Scalar for our email that is rfc822 compliant.

Notes

1const EMAIL_ADDRESS_REGEX =
2 /^[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])?)*$/;
3
4const validate = (value) => {
5 if (typeof value !== "string") {
6 throw new GraphQLError(`Value is not string: ${value}`);
7 }
8
9 if (!EMAIL_ADDRESS_REGEX.test(value)) {
10 throw new GraphQLError(`Value is not a valid email address: ${value}`);
11 }
12
13 return value;
14};
15
1const parseLiteral = (ast) => {
2 if (ast.kind !== Kind.STRING) {
3 throw new GraphQLError(
4 `Query error: Can only parse strings as email addresses but got a: ${ast.kind}`
5 );
6 }
7
8 return validate(ast.value);
9};
10
1const GraphQLEmailAddressConfig = {
2 name: "EmailAddress",
3 description: "A valid email address",
4 serialize: validate,
5 parseValue: validate,
6 parseLiteral,
7};
8
9const GraphQLEmailAddress = new GraphQLScalarType(GraphQLEmailAddressConfig);
10
1const typeDefs = `
2 scalar EmailAddress
3`;
4
5const resolvers = {
6 EmailAddress: GraphQLEmailAddress,
7};
8