如何手动将 apollo 自定义标量映射到客户端类型

How can I manually map apollo custom scalars to client side types

如何手动将 apollo 自定义标量映射到客户端类型?

我不想更改与 Field Policy 关联的类型。 (我正在尝试 essentially do this,即手动添加对自定义标量类型的支持)。服务器的值是 string 但我不想将其转换为 JS 数据(更具体地说是 luxon DateTime

我有这样的架构:

export interface SomeType {
  __typename: "SomeType";
  created: GraphQLDateTime;
}

我有这样的现场政策:

import { DateTime } from 'luxon'

const cache = new InMemoryCache({
    typePolicies: {
      SomeType: {
        fields: {
          created: {
            read: (created: string): DateTime => DateTime.fromISO(created)
          }
        }
      }
    }
  })

我有一个 graphqlScalars.d.ts 类型文件来提供自定义类型到 JS 类型的映射:

type GraphQLDateTime = string

我无法将我的类型定义文件切换为类似的文件,因为它会导致导入问题:

type GraphQLDateTime = DateTime

问题是,字段解析器按预期工作(即将我的 ISO8601 字符串转换为 luxon DateTime)但是 TS 类型系统(因为 graphqlScalars.d.ts 类型定义) 期望 createdstring 所以 DateTime 打字不可用。

这是 read 函数的类型:

export declare type FieldReadFunction<TExisting = any, TReadResult = TExisting> = (existing: SafeReadonly<TExisting> | undefined, options: FieldFunctionOptions) => TReadResult | undefined;

如何手动将 apollo 自定义标量映射到客户端类型?

引用 我能够使用导入语法按以下方式手动映射我的类型:

type GraphQLDateTime = import('@types/luxon').DateTime

现在在我的代码中 created(已通过 FieldPolicy 转换为正确的类型。