Skip to content

GQL @client directive fields should be elided for server-side consumption #6

@gjbadros

Description

@gjbadros

We use GraphQL and Apollo Client 3.x including some client-side generated fields using the @client directive in our .GQL files. Those @client fields are included in the server-side query which is a mistake -- they should be skipped because the server knows nothing about them. I fixed this for our case with a simple preprocessing step (see below) but it really should just be a configuration: omitFieldsDirectives: @client or even just understand @client natively.

Here's my addToPersistedOperations.js post-generation script that creates the files without the @client fields.

/* eslint-disable no-undef */
/* eslint-disable @typescript-eslint/no-var-requires */
// addToPersistedOperations.js
// TODO:BENJIE:: @client directive fields should be omitted
const map = require('../api/server-persisted-queries.json')
const fs = require('fs')
const fsp = fs.promises

async function main() {
  if (
    !fs.existsSync(`${__dirname}/../api/build/api/src/persisted_operations/`)
  ) {
    fs.mkdirSync(
      `${__dirname}/../api/build/api/src/persisted_operations/`,
      // eslint-disable-next-line no-octal
      0744
    )
  }
  await Promise.all(
    Object.entries(map).map(([hash, query]) => {
      // We used @client directive, but the graphql-codegen-persisted-ids plugin does not
      // know about the @client.  Luckily, all we have to do is remove those fields from
      // the server-side notion of the query (that means that the server-side hash will not
      // be accurate but that does not matter (at all I hope))
      const noClientDirectiveQuery = query.replace(
        /\n\s*\w+\s+@client\s*\n/g,
        '\n'
      )
      fsp.writeFile(
        `${__dirname}/../api/build/api/src/persisted_operations/${hash}.graphql`,
        noClientDirectiveQuery
      )
    })
  )
}

main().catch(e => {
  console.error(e)
  process.exit(1)
})

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions