Scalar Mappings
Scalar mappings allow you to define global type conversions from Go types to GraphQL scalars. This is especially useful for common types like UUIDs, timestamps, or custom value objects that should always map to the same GraphQL scalar regardless of where they appear in your schema.
How It Works
When a field's Go type matches a configured scalar mapping, GQLSchemaGen will:
- Use the mapped GraphQL scalar instead of generating a new type
- Auto-generate scalar declarations for custom scalars (non-built-in)
- Preserve array and nullability modifiers from the Go type
Configuration:
Go struct:
Generated schema:
Scalar Declaration Rules
Scalar declarations are automatically generated based on these rules:
Generated:
- Custom scalars used in the schema
- NOT in
known_scalarslist - NOT built-in GraphQL scalars
NOT Generated:
- Built-in scalars:
Int,Float,String,Boolean,ID - Scalars in
known_scalars(assumed defined elsewhere)
Example:
Result:
ID→ Not declared (built-in)DateTime→ Declared (custom, not in known_scalars)Upload→ Not declared (in known_scalars)
Multiple Type Mappings
You can map multiple Go types to the same GraphQL scalar:
This ensures consistency when different packages are used for the same concept (e.g., different UUID libraries).
Full Package Paths
Scalar mappings require full package paths, not just type names:
Common Scalar Mappings
Here are commonly used scalar mappings:
Per-Field Overrides
You can override scalar mappings for specific fields using the type: tag option:
Generated:
Nullability and Arrays
Scalar mappings preserve Go type modifiers:
Integration with Known Scalars
Scalar mappings work alongside known_scalars:
Use known_scalars when:
- Scalar is defined in another schema file
- Using third-party scalar definitions
- Integrating with gqlgen or other tools
Use scalars mappings when:
- Mapping Go types to scalars globally
- Want automatic scalar declarations
- Need consistent type conversions
Example:
Best Practices
- Use Full Paths: Always specify complete package paths
- Consistent UUIDs: Map all UUID libraries to the same scalar (usually
ID) - Time Types: Map
time.Timeto a customDateTimeorTimestampscalar - Document Custom Scalars: Add custom scalars to
known_scalarsif defined elsewhere - Avoid Over-Mapping: Only map types that truly represent the same GraphQL scalar
Once your scalar mappings are configured, run:
$ gqlschemagen generateto apply the mappings across your entire schema.