Skip to content

Add hooks to graphql-tag-pluck to modify its behaviorΒ #5127

@frandiox

Description

@frandiox

Hi, thanks for maintaining this repo!

Is your feature request related to a problem? Please describe.

I'm using graphql-codegen-generator, which relies internally on @graphql-tools/graphql-tag-pluck. I'm creating codegen utilities for @shopify/hydrogen using all of this, and I'd love to have some extra flexibility in two areas:

Detecting GQL in template literals

Right now it understands leading comments like /* GraphQL */ and supports the gqlMagicComment option to change the comment. However, we use comments inside the string itself, which is also valid for syntax highlights in VSCode:

const QUERY = `#graphql
  query { ...}
`;

This is not recognized by graphql-tag-pluck at the moment.

Extracting GQL strings from files

The integration I'm working on only uses strings, not AST. The problem I've found is that variables like ${FRAGMENT} are completely removed from the extracted string so we lose information.

Instead, I'd like to annotate the string with this ${FRAGMENT} somehow so that later we know how some queries depend on fragments. For example, by adding a comment to the string. For this, we'd need to change how the pluckStringFromFile function works.

Our target is to generate the following code:

interface GeneratedQueryTypes {
  '#graphql\n  query layout {\n    shop {\n      ...f1\n    }\n  }\n  #graphql\n  fragment f1 on Shop {\n    name\n    description\n  }\n\n': {
    return: LayoutQuery;
    variables: LayoutQueryVariables;
  };
  // ...
}

And, with that, we can match strings to variables and return types.

Describe the solution you'd like

It would be great if we can add a couple of hooks to modify how graphql-tag-pluck works internally (names TBD):

  • isGqlTemplateLiteral(node: Node, options: GqlOptions): boolean
  • pluckStringFromFile(code: string, node: Node, options: GqlOptions): string

Something like this example implementation. We would use the hooks like this to make codegen work with plain strings:

image


Let me know if this is something reasonable and I'll make a PR πŸ‘

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions