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:

  1. Use the mapped GraphQL scalar instead of generating a new type
  2. Auto-generate scalar declarations for custom scalars (non-built-in)
  3. Preserve array and nullability modifiers from the Go type

Configuration:

gqlschemagen.yml

Go struct:

user.go

Generated schema:

schema.graphqls

Scalar Declaration Rules

Scalar declarations are automatically generated based on these rules:

Generated:

  • Custom scalars used in the schema
  • NOT in known_scalars list
  • NOT built-in GraphQL scalars

NOT Generated:

  • Built-in scalars: Int, Float, String, Boolean, ID
  • Scalars in known_scalars (assumed defined elsewhere)

Example:

gqlschemagen.yml

Result:

  • ID → Not declared (built-in)
  • DateTimeDeclared (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:

gqlschemagen.yml

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:

gqlschemagen.yml

Per-Field Overrides

You can override scalar mappings for specific fields using the type: tag option:

user.go

Generated:

schema.graphqls

Nullability and Arrays

Scalar mappings preserve Go type modifiers:

examples.go

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:

gqlschemagen.yml

Best Practices

  1. Use Full Paths: Always specify complete package paths
  2. Consistent UUIDs: Map all UUID libraries to the same scalar (usually ID)
  3. Time Types: Map time.Time to a custom DateTime or Timestamp scalar
  4. Document Custom Scalars: Add custom scalars to known_scalars if defined elsewhere
  5. Avoid Over-Mapping: Only map types that truly represent the same GraphQL scalar

Once your scalar mappings are configured, run:

$ gqlschemagen generate

to apply the mappings across your entire schema.