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

标签 reactjs typescript graphql graphql-codegen

我有一个以下查询

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

我想过滤这样的节点列表

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 }}
    />
  )
}

问题是 @graphql-codegen/cli 不会导出 NodeType 的类型。

这是我的代码生成配置

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

哪个配置使codegen导出NodeType类型或如何通过ts实现它

最佳答案

Codegen 不会为操作的每个部分生成独立类型。 但您可以轻松地从操作类型中提取所需的部分。应该是这样的: type NodeType = AdvertCustomFieldsQuery['advertCustomFields']['nodes'][number]

关于reactjs - 使用 @graphql-codegen/cli 获取 graphql 查询中的子类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74811628/

相关文章:

typescript - 导入带有可选链接的模块时出错

TypeScript:控制台在 IE 中未定义

ruby-on-rails - 如何使用 graphql-ruby 指定多态类型?

javascript - 如何将所有值添加到该数组中?每次创建一个新的 CLIENT 数组并向其推送值

javascript - 即使reactjs收到了数据,为什么我的笔记没有显示/更新?

javascript - Redux reducers 初始化相同的状态键

javascript - 使用 fetch 更新状态然后在 useEffect 中使用状态不起作用

sql-server - 元素隐式具有 'any' 类型,因为类型 'string' 的表达式不能用于索引类型 'Type'

graphql - 动态 GraphQL 架构?

javascript - 使用 graphql 模式语言的嵌套查询