【发布时间】:2021-02-26 09:18:18
【问题描述】:
如何手动将 apollo 自定义标量映射到客户端类型?
我不想更改与字段策略关联的类型。 (我正在尝试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 类型定义)需要 created成为string 所以DateTime 打字不可用。
这是read函数的输入:
export declare type FieldReadFunction<TExisting = any, TReadResult = TExisting> = (existing: SafeReadonly<TExisting> | undefined, options: FieldFunctionOptions) => TReadResult | undefined;
如何手动将 apollo 自定义标量映射到客户端类型?
【问题讨论】:
标签: typescript graphql apollo apollo-client