简体   繁体   English

从 TypeScript 类型定义或 Z524DE3D2ADE4544176F60702B3FFB6 定义生成 JavaScript 空 object

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

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.我在带有 Apollo 客户端的项目中使用 GraphQL,当我使用writeFragment时,我必须将 object 形状与片段定义相匹配。 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.我想从gql片段生成一个空的 JavaScript object 。 eg例如

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选项 1 是使用已经存在的东西
  • Option 2 would be to write my own function选项 2 是编写我自己的 function
  • Option 3 is:选项 3 是:

I'm using GraphQL Code Generator to generate TypeScript definitions from my code, so I have code like this:我正在使用GraphQL 代码生成器从我的代码中生成 TypeScript 定义,所以我有这样的代码:

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?有没有办法把它变成我想要的?

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. GraphQL Codegen 的目标之一是让您轻松自定义 output,并根据您的需要添加自定义行为。

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 https://graphql-code-generator.com/docs/custom-codegen/write-your-plugin

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM