首页 > 解决方案 > 如何从 graphql 内省结果中导出 typescript 类型?

问题描述

在 react-admin 应用程序中,我有一个基于ra-postgraphile. 在自定义组件中,我想使用记录类型查询该数据提供者以提高类型安全性。我打算按照他们文档中描述的提示来做,就像这样:

dataProvider.getOne<Product>('products', { id: 123 })
//                  ^^^^^^^ the record type
    .then(({ data }) => {
        //     \- type of data is Product
        // ...
    })

如何Product根据 IntrospectionQuery 的自省结果中的类型创建类型?

实际上,我什至不知道如何从 react-admin 首先呈现的组件中获取自省结果。

这是描述 Product 的自省结果中的 types 数组中的类型。

{
  "kind": "OBJECT",
  "name": "Product",
  "description": null,
  "fields": [{
      "name": "nodeId",
      "description": "A globally unique identifier. Can be used in various places throughout the system to identify this single value.",
      "args": [],
      "type": {
        "kind": "NON_NULL",
        "name": null,
        "ofType": {
          "kind": "SCALAR",
          "name": "ID",
          "ofType": null,
          "__typename": "__Type"
        },
        "__typename": "__Type"
      },
      "isDeprecated": false,
      "deprecationReason": null,
      "__typename": "__Field"
    },
    {
      "name": "id",
      "description": null,
      "args": [],
      "type": {
        "kind": "NON_NULL",
        "name": null,
        "ofType": {
          "kind": "SCALAR",
          "name": "UUID",
          "ofType": null,
          "__typename": "__Type"
        },
        "__typename": "__Type"
      },
      "isDeprecated": false,
      "deprecationReason": null,
      "__typename": "__Field"
    },
    {
      "name": "productCode",
      "description": null,
      "args": [],
      "type": {
        "kind": "NON_NULL",
        "name": null,
        "ofType": {
          "kind": "SCALAR",
          "name": "Int",
          "ofType": null,
          "__typename": "__Type"
        },
        "__typename": "__Type"
      },
      "isDeprecated": false,
      "deprecationReason": null,
      "__typename": "__Field"
    },
    {
      "name": "timestamp",
      "description": null,
      "args": [],
      "type": {
        "kind": "SCALAR",
        "name": "Datetime",
        "ofType": null,
        "__typename": "__Type"
      },
      "isDeprecated": false,
      "deprecationReason": null,
      "__typename": "__Field"
    }
  ],
  "inputFields": null,
  "interfaces": [{
    "kind": "INTERFACE",
    "name": "Node",
    "ofType": null,
    "__typename": "__Type"
  }],
  "enumValues": null,
  "possibleTypes": null,
  "__typename": "__Type"
}

标签: typescriptgraphqlreact-adminintrospection

解决方案


我写了自己的 graphqlProvider。我正在使用模式预加载 Introspection 它作为我的提供者的上下文

get-graphql-schema http: // localhost: 8557 --json -> src \\ dataProvider \\ Core \\ schema.json

我的项目中没有基于动态访问的架构,所以这种方法对我来说是最佳的。


推荐阅读