Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
gjbadros opened this issue May 25, 2021 · 0 comments

Comments

@gjbadros
Copy link

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)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant