Using the RegularExpression scalar
Using the RegularExpression scalar — GraphQL Scalars documentation.
First an explanation: To create a new scalar type for the GraphQL schema language, you must create
an instance of a new GraphQLScalarType object that implements three general functions/methods:
serialize, parseValue and parseLiteral which are used at different stages of processing your
GraphQL types during queries and mutations. So creating a new scalar looks like this:
Given this, if we want to create a new type that is essentially the same except for one little
customizable aspect (e.g., a regular expression type that has all the same code except the regex is
different) then we need to dynamically generate a new GraphQLScalarType object given some
parameters. That’s the approach we take here.
Therefore, the RegularExpression scalar type is really a GraphQLScalarType object generator
that takes two arguments:
- A name
- The regex you want it to use
So to create a new scalar for a given regex, you will do this:
Now MyRegexType is your new GraphQL scalar type that will enforce a value of, in this case, “ABC”.
Add your new scalar type to your resolver map:
And to your schema:
That’s it. Now you can use MyRegexType as a type in the rest of your schema.
RegularExpression options
There is an optional third options argument to the RegularExpression constructor that can be used
like this: