Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GraphQL requesting fields that don't exist without error

Tags:

graphql

I'm trying to handle backwards compatibility with my GraphQL API.

We have on-premise servers that get periodically updated based off of when they connect to the internet. We have a Mobile app that talks to the on-premise server.

Problem

We get into an issue where the Mobile app is up to date and the on-premise server isn't. When a change in the Schema occurs, it causes issues.

Example

Product version 1

type Product {
 name: String
}

Product version 2

type Product {
 name: String
 account: String
}

New version of mobile app asks for:

product(id: "12345") {
  name
  account
}

Because account is not valid in version 1, I get the error:

"Cannot query field \"account\" on type \"Product\"."

Does anyone know how I can avoid this issue so I don't recieve this particular error. I'm totally fine with account coming back with Null or just some other plan of attack for updating Schema's. But having it completely blow up with no response is not good

like image 508
bryan Avatar asked Feb 18 '26 07:02

bryan


1 Answers

Your question did not specify what you're actually using on the backend. But it should be possible to customize the validation rules a GraphQL service uses in any implementation based on the JavaScript reference implementation. Here's how you do it in GraphQL.js:

const { execute, parse, specifiedRules, validate } = require('graphql')

const validationRules = specifiedRules.filter(rule => rule.name !== 'FieldsOnCorrectType')
const document = parse(someQuery)
const errors = validate(schema, document, validationRules)
const data = await execute({ schema, document })

By omitting the FieldsOnCorrectType rule, you won't get any errors and unrecognized fields will simply be left off the response.

But you really shouldn't do that.

Modifying the validation rules will result in spec-breaking changes to your server, which can cause issues with client libraries and other tools you use.

This issue really boils down to your deployment process. You should not push new versions of the client that depend on a newer version of the server API until that version is deployed to the server. Period. That would hold true regardless of whether you're using GraphQL, REST, SOAP, etc.

like image 122
Daniel Rearden Avatar answered Feb 20 '26 02:02

Daniel Rearden