简体   繁体   English

使用@graphql-codegen/cli 在 graphql 查询中获取子类型

[英]get sub types in graphql query using @graphql-codegen/cli

I have a below query我有以下查询

export const GET_ALL_ADVERT_CUSTOM_FIELD = gql(`
  query advertCustomFields {
    advertCustomFields {
      nodes {
        slug
        valueType
        displayName
        description
        canRead
      }
    }
  }
`)

And I would like to get the list filtered of nodes like this我想像这样过滤节点列表

import { Props as SelectProps } from 'react-select'
import React, { FC, useState } from 'react'
import ObjectSelector from 'components/Common/ObjectSelector'
import OptionWithDescription from './OptionWithDescription'
import { useQuery } from '@apollo/client'
import { AdvertCustomFieldsDocument } from '__generated__/graphql'

export const AdvertCustomFieldSelector: FC<SelectProps> = (props) => {
  const [data, setData] = useState<NodeType[]>()
  useQuery(AdvertCustomFieldsDocument, {
    onCompleted: (res) => {
      const filterData = res.advertCustomFields?.nodes?.filter((e) => e.canRead)
      setData(filterData)
    },
  })

  return (
    <ObjectSelector<Node>
      name={props.name}
      onChange={props.onChange}
      options={data as any}
      getOptionLabel={(option) => option?.displayName as string}
      getOptionValue={(option) => `${option.slug}`}
      components={{ Option: OptionWithDescription }}
    />
  )
}

The thing is @graphql-codegen/cli does not export type for the NodeType.问题是@graphql-codegen/cli不会导出 NodeType 的类型。

This is my codegen config这是我的代码生成配置

import { CodegenConfig } from '@graphql-codegen/cli'

const config: CodegenConfig = {
  schema: './app/graphql/schema.graphql',
  documents: ['./facerberus/components/**/*.ts'],
  ignoreNoDocuments: true, // for better experience with the watcher
  generates: {
    './facerberus/__generated__/': {
      preset: 'client',
      plugins: [],
      presetConfig: {
        gqlTagName: 'gql',
      },
    },
  },
}

export default config

which config to make codegen export type of NodeType or how to achieve it via ts哪个配置使 NodeType 的代码生成导出类型或如何通过 ts 实现它

Codegen doesn't generate a standalone type for every part of the operaation. Codegen 不会为操作的每个部分生成独立类型。 But you can easily extract the needed part from the operation type.但是您可以轻松地从操作类型中提取需要的部分。 Should be something like this: type NodeType = AdvertCustomFieldsQuery['advertCustomFields']['nodes'][number]应该是这样的: type NodeType = AdvertCustomFieldsQuery['advertCustomFields']['nodes'][number]

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

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