Generate JavaScript empty object from TypeScript type definition, or GraphQL fragment definition

Viewed 394

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?

1 Answers

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

Related