9

I'm using GraphQL in a project with the Apollo client, and when I use writeFragment I have to match the object shape to the fragment definition. I'm doing this manually right now, but it results in a lot of unnecessary code and makes things fragile for when the fragment definition changes.

I'd like to generate an empty JavaScript object from the gql fragment. e.g

export const instructorFragment = gql`
  fragment InstructorDetails on InstructorProfile {
    id
    user_id
    picture_url
    title
    bio

    tags {
      ...TagDetails
    }
  }
  ${tagFragment}
`;

export const tagFragment = gql`
  fragment TagDetails on Tag {
    id
    label
  }
`;

Should generate something like:

{
    id: null,
    user_id: null,
    picture_url: null,
    title: null,
    bio: null,
    tags: {
        id: null,
        label: null
    }
}

The fragment objects have enough information to do this, but I haven't been able to find a library despite much Googling.

  • Option 1 would be to use something that already exists
  • Option 2 would be to write my own function
  • Option 3 is:

I'm using GraphQL Code Generator to generate TypeScript definitions from my code, so I have code like this:

export type InstructorProfile = {
  __typename?: 'InstructorProfile';
  id: Scalars['ID'];
  user_id?: Maybe<Scalars['ID']>;
  picture_url?: Maybe<Scalars['String']>;
  title?: Maybe<Scalars['String']>;
  bio?: Maybe<Scalars['String']>;
  tags?: Maybe<Array<Maybe<Tag>>>;
};

export type Tag = {
  __typename?: 'Tag';
  id: Scalars['ID'];
  label: Scalars['String'];
};

Is there a way to turn this into what I want instead?

Senthurkumaran
  • 1,738
  • 2
  • 19
  • 29
  • 1
    You can create types from values. You cannot create values from types. – Aluan Haddad Aug 06 '20 at 06:07
  • 1
    I'm not sure I entirely understood what you are doing, but, `TypeScript` is a compile time thing, the moment you try to run a code, it is `JavaScript`. And as we know already, `JavaScript` does not have concept of types.So, the idea of running the code and generating something based on `TypeScript` types will not really work. – Arghya C Aug 12 '20 at 06:20

1 Answers1

0

The tool you list above to generate the type defs, says the following on it’s website.

One of the goals of GraphQL Codegen is to allow you to easily customize the output, and add custom behaviour according to your needs.

So it should be possible to write a custom plugin to do what your after, here’s the link to getting started on plugin development for this.

https://graphql-code-generator.com/docs/custom-codegen/write-your-plugin

David Bradshaw
  • 11,859
  • 3
  • 41
  • 70