|
| 1 | +--- |
| 2 | +title: Best Practices for Custom Scalars |
| 3 | +--- |
| 4 | + |
| 5 | +# Custom Scalars: Best Practices and Testing |
| 6 | + |
| 7 | +Custom scalars must behave predictably and clearly. To maintain a consistent, reliable |
| 8 | +schema, follow these best practices. |
| 9 | + |
| 10 | +### Document expected formats and validation |
| 11 | + |
| 12 | +Provide a clear description of the scalar’s accepted input and output formats. For example, a |
| 13 | +`DateTime` scalar should explain that it expects [ISO-8601](https://www.iso.org/iso-8601-date-and-time-format.html) strings ending with `Z`. |
| 14 | + |
| 15 | +Clear descriptions help clients understand valid input and reduce mistakes. |
| 16 | + |
| 17 | +### Validate consistently across `parseValue` and `parseLiteral` |
| 18 | + |
| 19 | +Clients can send values either through variables or inline literals. |
| 20 | +Your `parseValue` and `parseLiteral` functions should apply the same validation logic in |
| 21 | +both cases. |
| 22 | + |
| 23 | +Use a shared helper to avoid duplication: |
| 24 | + |
| 25 | +```js |
| 26 | +function parseDate(value) { |
| 27 | + const date = new Date(value); |
| 28 | + if (isNaN(date.getTime())) { |
| 29 | + throw new TypeError(`DateTime cannot represent an invalid date: ${value}`); |
| 30 | + } |
| 31 | + return date; |
| 32 | +} |
| 33 | +``` |
| 34 | + |
| 35 | +Both `parseValue` and `parseLiteral` should call this function. |
| 36 | + |
| 37 | +### Return clear errors |
| 38 | + |
| 39 | +When validation fails, throw descriptive errors. Avoid generic messages like "Invalid input." |
| 40 | +Instead, use targeted messages that explain the problem, such as: |
| 41 | + |
| 42 | +```text |
| 43 | +DateTime cannot represent an invalid date: `abc123` |
| 44 | +``` |
| 45 | + |
| 46 | +Clear error messages speed up debugging and make mistakes easier to fix. |
| 47 | + |
| 48 | +### Serialize consistently |
| 49 | + |
| 50 | +Always serialize internal values into a predictable format. |
| 51 | +For example, a `DateTime` scalar should always produce an ISO string, even if its |
| 52 | +internal value is a `Date` object. |
| 53 | + |
| 54 | +```js |
| 55 | +serialize(value) { |
| 56 | + if (!(value instanceof Date)) { |
| 57 | + throw new TypeError('DateTime can only serialize Date instances'); |
| 58 | + } |
| 59 | + return value.toISOString(); |
| 60 | +} |
| 61 | +``` |
| 62 | + |
| 63 | +Serialization consistency prevents surprises on the client side. |
| 64 | + |
| 65 | +## Testing custom scalars |
| 66 | + |
| 67 | +Testing ensures your custom scalars work reliably with both valid and invalid inputs. |
| 68 | +Tests should cover three areas: coercion functions, schema integration, and error handling. |
| 69 | + |
| 70 | +### Unit test serialization and parsing |
| 71 | + |
| 72 | +Write unit tests for each function: `serialize`, `parseValue`, and `parseLiteral`. |
| 73 | +Test with both valid and invalid inputs. |
| 74 | + |
| 75 | +```js |
| 76 | +describe('DateTime scalar', () => { |
| 77 | + it('serializes Date instances to ISO strings', () => { |
| 78 | + const date = new Date('2024-01-01T00:00:00Z'); |
| 79 | + expect(DateTime.serialize(date)).toBe('2024-01-01T00:00:00.000Z'); |
| 80 | + }); |
| 81 | + |
| 82 | + it('throws if serializing a non-Date value', () => { |
| 83 | + expect(() => DateTime.serialize('not a date')).toThrow(TypeError); |
| 84 | + }); |
| 85 | + |
| 86 | + it('parses ISO strings into Date instances', () => { |
| 87 | + const result = DateTime.parseValue('2024-01-01T00:00:00Z'); |
| 88 | + expect(result).toBeInstanceOf(Date); |
| 89 | + expect(result.toISOString()).toBe('2024-01-01T00:00:00.000Z'); |
| 90 | + }); |
| 91 | + |
| 92 | + it('throws if parsing an invalid date string', () => { |
| 93 | + expect(() => DateTime.parseValue('invalid-date')).toThrow(TypeError); |
| 94 | + }); |
| 95 | +}); |
| 96 | +``` |
| 97 | + |
| 98 | +### Test custom scalars in a schema |
| 99 | + |
| 100 | +Integrate the scalar into a schema and run real GraphQL queries to validate end-to-end behavior. |
| 101 | + |
| 102 | +```js |
| 103 | +const { graphql, buildSchema } = require('graphql'); |
| 104 | + |
| 105 | +const schema = buildSchema(` |
| 106 | + scalar DateTime |
| 107 | +
|
| 108 | + type Query { |
| 109 | + now: DateTime |
| 110 | + } |
| 111 | +`); |
| 112 | + |
| 113 | +const rootValue = { |
| 114 | + now: () => new Date('2024-01-01T00:00:00Z'), |
| 115 | +}; |
| 116 | + |
| 117 | +async function testQuery() { |
| 118 | + const response = await graphql({ |
| 119 | + schema, |
| 120 | + source: '{ now }', |
| 121 | + rootValue, |
| 122 | + }); |
| 123 | + console.log(response); |
| 124 | +} |
| 125 | + |
| 126 | +testQuery(); |
| 127 | +``` |
| 128 | + |
| 129 | +Schema-level tests verify that the scalar behaves correctly during execution, not just |
| 130 | +in isolation. |
| 131 | + |
| 132 | +## Common use cases for custom scalars |
| 133 | + |
| 134 | +Custom scalars solve real-world needs by handling types that built-in scalars don't cover. |
| 135 | + |
| 136 | +- `DateTime`: Serializes and parses ISO-8601 date-time strings. |
| 137 | +- `Email`: Validates syntactically correct email addresses. |
| 138 | + |
| 139 | +```js |
| 140 | +function validateEmail(value) { |
| 141 | + const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; |
| 142 | + if (!emailRegex.test(value)) { |
| 143 | + throw new TypeError(`Email cannot represent invalid email address: ${value}`); |
| 144 | + } |
| 145 | + return value; |
| 146 | +} |
| 147 | +``` |
| 148 | + |
| 149 | +- `URL`: Ensures well-formatted, absolute URLs. |
| 150 | + |
| 151 | +```js |
| 152 | +function validateURL(value) { |
| 153 | + try { |
| 154 | + new URL(value); |
| 155 | + return value; |
| 156 | + } catch { |
| 157 | + throw new TypeError(`URL cannot represent an invalid URL: ${value}`); |
| 158 | + } |
| 159 | +} |
| 160 | +``` |
| 161 | + |
| 162 | +- `JSON`: Represents arbitrary JSON structures, but use carefully because it bypasses |
| 163 | +GraphQL's strict type checking. |
| 164 | + |
| 165 | +## When to use existing libraries |
| 166 | + |
| 167 | +Writing scalars is deceptively tricky. Validation edge cases can lead to subtle bugs if |
| 168 | +not handled carefully. |
| 169 | + |
| 170 | +Whenever possible, use trusted libraries like [`graphql-scalars`](https://www.npmjs.com/package/graphql-scalars). They offer production-ready |
| 171 | +scalars for DateTime, EmailAddress, URL, UUID, and many others. |
| 172 | + |
| 173 | +### Example: Handling email validation |
| 174 | + |
| 175 | +Handling email validation correctly requires dealing with Unicode, quoted local parts, and |
| 176 | +domain validation. Rather than writing your own regex, it’s better to use a library scalar |
| 177 | +that's already validated against standards. |
| 178 | + |
| 179 | +If you need domain-specific behavior, you can wrap an existing scalar with custom rules: |
| 180 | + |
| 181 | +```js |
| 182 | +const { EmailAddressResolver } = require('graphql-scalars'); |
| 183 | + |
| 184 | +const StrictEmail = new GraphQLScalarType({ |
| 185 | + ...EmailAddressResolver, |
| 186 | + parseValue(value) { |
| 187 | + if (!value.endsWith('@example.com')) { |
| 188 | + throw new TypeError('Only example.com emails are allowed.'); |
| 189 | + } |
| 190 | + return EmailAddressResolver.parseValue(value); |
| 191 | + }, |
| 192 | +}); |
| 193 | +``` |
| 194 | + |
| 195 | +By following these best practices and using trusted tools where needed, you can build custom |
| 196 | +scalars that are reliable, maintainable, and easy for clients to work with. |
| 197 | + |
| 198 | +## Additional resources |
| 199 | + |
| 200 | +- [GraphQL Scalars by The Guild](https://the-guild.dev/graphql/scalars): A production-ready |
| 201 | +library of common custom scalars. |
| 202 | +- [GraphQL Scalars Specification](https://github.com/graphql/graphql-scalars): This |
| 203 | +specification is no longer actively maintained, but useful for historical context. |
0 commit comments