feat: scalar coercion via resolver map override (Approach 1 — Global) - #691
Closed
mendescamara wants to merge 1 commit into
Closed
feat: scalar coercion via resolver map override (Approach 1 — Global)#691mendescamara wants to merge 1 commit into
mendescamara wants to merge 1 commit into
Conversation
graphql-tools v3.x replaces schema._typeMap entries when a GraphQLScalarType instance is provided in the resolver map, safely overriding Int/Float/String without mutating the global graphql package singletons. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
mendescamara
requested review from
RodrigoTadeuF,
gabpaladino and
leo-prange-vtex
and removed request for
a team
May 6, 2026 13:34
Contributor
|
Hi! I'm VTEX IO CI/CD Bot and I'll be helping you to publish your app! 🤖 Please select which version do you want to release:
And then you just need to merge your PR when you are ready! There is no need to create a release commit/tag.
|
|
mendescamara
added a commit
that referenced
this pull request
May 7, 2026
… (Approach 2) (#692) ## Context GraphQL's built-in scalars (`Int`, `Float`, `String`) reject values that are technically compatible but typed differently — e.g. `"20"` for an `Int` argument. A global override (see [Approach 1](../pull/691)) removes strict validation for the entire schema, which may be undesirable. This PR explores **Approach 2: surgical coercion** via a `@coerce` schema directive that can be applied selectively to individual `INPUT_FIELD_DEFINITION` or `ARGUMENT_DEFINITION` locations. ## How it works The directive follows the exact same pattern as [`@sanitize` in node-vtex-api](https://github.com/vtex/node-vtex-api/blob/master/src/service/worker/runtime/graphql/schema/schemaDirectives/sanitize.ts): a `SchemaDirectiveVisitor` subclass that **replaces the field's scalar type at schema-build time** with a coercible version. ``` makeExecutableSchema → applySchemaDirectives → Coerce.visitInputFieldDefinition(field) → field.type = replaceWithCoercible(field.type) // swap Int → CoercibleInt ``` `replaceWithCoercible` walks `GraphQLNonNull` and `GraphQLList` wrappers recursively to reach the inner named scalar, then swaps it with the matching coercible instance. Only `Int`, `Float`, and `String` have coercible versions; other types pass through unchanged. ## Changes ### `node/directives/coerce.ts` (new) - `Coerce extends SchemaDirectiveVisitor` with `visitInputFieldDefinition` and `visitArgumentDefinition` - Three coercible scalar instances (same logic as Approach 1, but scoped to this directive) - `replaceWithCoercible` helper that unwraps `NonNull`/`List` before substituting ### `node/directives/index.ts` Registers `coerce: Coerce` in the `schemaDirectives` map. ### `graphql/schema.graphql` Declares the directive: ```graphql directive @Coerce on INPUT_FIELD_DEFINITION | ARGUMENT_DEFINITION ``` ### `graphql/types/Shipping.graphql` Applies the directive as a concrete example: ```graphql # Before input ShippingItem { quantity: String # typed as String for legacy reasons } # After input ShippingItem { quantity: Int @Coerce # semantically correct, still accepts "20" } ``` `ShippingItem.quantity` was previously typed as `String` even though it represents an integer count. With `@coerce` it becomes `Int` (correct semantic type) while retaining backward compatibility for clients that send it as a string. ## Trade-offs | | Approach 2 (this PR) | |---|---| | **Scope** | Only fields explicitly annotated with `@coerce` | | **SDL changes** | Directive declaration + annotation per field | | **Risk** | Minimal — strict validation preserved everywhere else | | **Maintenance** | Each new field needs the annotation | > Compare with [Approach 1 — global scalar override](../pull/691) which coerces all fields automatically. ## References - node-vtex-api `@sanitize` directive — `SchemaDirectiveVisitor` replacing field types at build time - `graphql-tools` v3.x `SchemaDirectiveVisitor` — supports `visitInputFieldDefinition` and `visitArgumentDefinition` - `graphql@0.13.2` scalar resolution flow: `parseLiteral` for inline values, `parseValue` for variables 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Context
GraphQL's built-in scalars (
Int,Float,String) have strictparseValueandparseLiteralimplementations. When clients or upstream systems send values in a compatible but different format — e.g."20"instead of20for anIntfield — the operation fails at the scalar validation layer.This PR explores Approach 1: global interception by replacing the built-in scalars in the schema's type map.
How it works
graphql-toolsv3.x (makeExecutableSchema) processes the resolver map viaaddResolversToSchema. When it finds aGraphQLScalarTypeinstance (not just a plain object) registered under a built-in scalar name (Int,Float,String), it replaces the entry inschema._typeMap[name]— the schema's own private type registry. This is safe because:GraphQLInt/GraphQLFloat/GraphQLStringsingletons from thegraphqlpackage.serializeis delegated unchanged to the original scalar, so output coercion is not affected.Changes
node/scalars/index.ts(new)Three
GraphQLScalarTypeinstances namedInt,Float, andString:parseValuebehaviorparseLiteraladditionIntparseInt(String(value))— accepts"20",20.9Kind.STRINGliteralsFloatparseFloat(String(value))— accepts"3.14",3Kind.STRING,Kind.INTliteralsStringString(value)— accepts numbers, booleansKind.INT,Kind.FLOAT,Kind.BOOLEANliteralsnode/resolvers/index.tsAdds
Int,Float,Stringentries pointing to the coercible scalar instances.Trade-offs
"abc"for anIntthrows at runtime instead of schema validation timeReferences
graphql-toolsv3.xaddResolversToSchema— handlesGraphQLScalarTypeinstances by replacingschema._typeMap[name]@sanitizedirective — established precedent of replacing scalar types at schema-build timegraphql@0.13.2scalar resolution flow:parseLiteralfor inline values,parseValuefor variables🤖 Generated with Claude Code