gpt4 book ai didi

typescript - 如何将 GraphQL 与 TypeScript 和 graphql-code-generator 生成的类型一起使用?

转载 作者:行者123 更新时间:2023-12-02 03:08:15 29 4
gpt4 key购买 nike

我正在关注 Apollo Docs tutorial使用 TypeScript 构建 Apollo 服务器(Express),我也在使用 GraphQL Code Generator根据我的 GraphQL 架构生成必要的类型。

这是我当前的codegen.json配置:

{
"schema": "./lib/schema/index.graphql",
"generates": {
"./dist/typings/graphql/schema.d.ts": {
"plugins": [
"typescript",
"typescript-resolvers"
],
"config": {
"typesPrefix": "GQL",
"skipTypename": true,
"noSchemaStitching": true,
"useIndexSignature": true
}
}
}
}

这是我当前基于教程的 GraphQL 模式(它并不完整,我还没有完成整个事情,我已经修剪了一些东西以使示例更小):

type Query {
launch(id: ID!): Launch
}

type Launch {
id: ID!
site: String
mission: Mission
}

enum PatchSize {
SMALL
LARGE
}

type Mission {
name: String
missionPatch(mission: String, size: PatchSize): String
}

生成以下 TypeScript 类型:

import { GraphQLResolveInfo } from 'graphql';
export type Maybe<T> = T | null;
export type RequireFields<T, K extends keyof T> = { [X in Exclude<keyof T, K>]?: T[X] } & { [P in K]-?: NonNullable<T[P]> };
/** All built-in and custom scalars, mapped to their actual values */
export type Scalars = {
ID: string,
String: string,
Boolean: boolean,
Int: number,
Float: number,
};

export type GQLLaunch = {
id: Scalars['ID'],
site?: Maybe<Scalars['String']>,
mission?: Maybe<GQLMission>,
};

export type GQLMission = {
name?: Maybe<Scalars['String']>,
missionPatch?: Maybe<Scalars['String']>,
};


export type GQLMissionMissionPatchArgs = {
mission?: Maybe<Scalars['String']>,
size?: Maybe<GQLPatchSize>
};

export enum GQLPatchSize {
Small = 'SMALL',
Large = 'LARGE'
}

export type GQLQuery = {
launch?: Maybe<GQLLaunch>,
};


export type GQLQueryLaunchArgs = {
id: Scalars['ID']
};

export type WithIndex<TObject> = TObject & Record<string, any>;
export type ResolversObject<TObject> = WithIndex<TObject>;

export type ResolverTypeWrapper<T> = Promise<T> | T;

export type ResolverFn<TResult, TParent, TContext, TArgs> = (
parent: TParent,
args: TArgs,
context: TContext,
info: GraphQLResolveInfo
) => Promise<TResult> | TResult;

export type Resolver<TResult, TParent = {}, TContext = {}, TArgs = {}> = ResolverFn<TResult, TParent, TContext, TArgs>;

export type SubscriptionSubscribeFn<TResult, TParent, TContext, TArgs> = (
parent: TParent,
args: TArgs,
context: TContext,
info: GraphQLResolveInfo
) => AsyncIterator<TResult> | Promise<AsyncIterator<TResult>>;

export type SubscriptionResolveFn<TResult, TParent, TContext, TArgs> = (
parent: TParent,
args: TArgs,
context: TContext,
info: GraphQLResolveInfo
) => TResult | Promise<TResult>;

export interface SubscriptionSubscriberObject<TResult, TKey extends string, TParent, TContext, TArgs> {
subscribe: SubscriptionSubscribeFn<{ [key in TKey]: TResult }, TParent, TContext, TArgs>;
resolve?: SubscriptionResolveFn<TResult, { [key in TKey]: TResult }, TContext, TArgs>;
}

export interface SubscriptionResolverObject<TResult, TParent, TContext, TArgs> {
subscribe: SubscriptionSubscribeFn<any, TParent, TContext, TArgs>;
resolve: SubscriptionResolveFn<TResult, any, TContext, TArgs>;
}

export type SubscriptionObject<TResult, TKey extends string, TParent, TContext, TArgs> =
| SubscriptionSubscriberObject<TResult, TKey, TParent, TContext, TArgs>
| SubscriptionResolverObject<TResult, TParent, TContext, TArgs>;

export type SubscriptionResolver<TResult, TKey extends string, TParent = {}, TContext = {}, TArgs = {}> =
| ((...args: any[]) => SubscriptionObject<TResult, TKey, TParent, TContext, TArgs>)
| SubscriptionObject<TResult, TKey, TParent, TContext, TArgs>;

export type TypeResolveFn<TTypes, TParent = {}, TContext = {}> = (
parent: TParent,
context: TContext,
info: GraphQLResolveInfo
) => Maybe<TTypes>;

export type NextResolverFn<T> = () => Promise<T>;

export type DirectiveResolverFn<TResult = {}, TParent = {}, TContext = {}, TArgs = {}> = (
next: NextResolverFn<TResult>,
parent: TParent,
args: TArgs,
context: TContext,
info: GraphQLResolveInfo
) => TResult | Promise<TResult>;

/** Mapping between all available schema types and the resolvers types */
export type GQLResolversTypes = ResolversObject<{
Query: ResolverTypeWrapper<{}>,
ID: ResolverTypeWrapper<Scalars['ID']>,
Launch: ResolverTypeWrapper<GQLLaunch>,
String: ResolverTypeWrapper<Scalars['String']>,
Mission: ResolverTypeWrapper<GQLMission>,
PatchSize: GQLPatchSize,
Boolean: ResolverTypeWrapper<Scalars['Boolean']>,
}>;

/** Mapping between all available schema types and the resolvers parents */
export type GQLResolversParentTypes = ResolversObject<{
Query: {},
ID: Scalars['ID'],
Launch: GQLLaunch,
String: Scalars['String'],
Mission: GQLMission,
PatchSize: GQLPatchSize,
Boolean: Scalars['Boolean'],
}>;

export type GQLLaunchResolvers<ContextType = any, ParentType extends GQLResolversParentTypes['Launch'] = GQLResolversParentTypes['Launch']> = ResolversObject<{
id?: Resolver<GQLResolversTypes['ID'], ParentType, ContextType>,
site?: Resolver<Maybe<GQLResolversTypes['String']>, ParentType, ContextType>,
mission?: Resolver<Maybe<GQLResolversTypes['Mission']>, ParentType, ContextType>,
}>;

export type GQLMissionResolvers<ContextType = any, ParentType extends GQLResolversParentTypes['Mission'] = GQLResolversParentTypes['Mission']> = ResolversObject<{
name?: Resolver<Maybe<GQLResolversTypes['String']>, ParentType, ContextType>,
missionPatch?: Resolver<Maybe<GQLResolversTypes['String']>, ParentType, ContextType, GQLMissionMissionPatchArgs>,
}>;

export type GQLQueryResolvers<ContextType = any, ParentType extends GQLResolversParentTypes['Query'] = GQLResolversParentTypes['Query']> = ResolversObject<{
launch?: Resolver<Maybe<GQLResolversTypes['Launch']>, ParentType, ContextType, RequireFields<GQLQueryLaunchArgs, 'id'>>,
}>;

export type GQLResolvers<ContextType = any> = ResolversObject<{
Launch?: GQLLaunchResolvers<ContextType>,
Mission?: GQLMissionResolvers<ContextType>,
Query?: GQLQueryResolvers<ContextType>,
}>;

这是我的 resolvers.ts 文件:

import { GQLPatchSize } from '@typings/graphql/schema';
import { GQLResolvers } from '@typings/graphql/schema';

const resolvers: GQLResolvers = {
Query: {
launch: (_, args, { dataSources }) => {
return dataSources.launchesAPI.getLaunchById(args);
},
},
Mission: {
missionPatch: (mission, { size } = { size: GQLPatchSize.Large }) => {
return size === 'SMALL' ? mission.missionPatchSmall : mission.missionPatchLarge;
},
},
};

export { resolvers };

最后,我的 launches.ts 文件包含 LaunchesAPI 类:

import { GQLLaunch } from '@typings/graphql/schema';
import { GQLQueryLaunchArgs } from '@typings/graphql/schema';
import { RESTDataSource } from 'apollo-datasource-rest';

const SPACEX_API_ENDPOINT = 'https://api.spacexdata.com/v3/';

class LaunchesAPI extends RESTDataSource {
constructor() {
super();

this.baseURL = SPACEX_API_ENDPOINT;
}

async getLaunchById({ id }: GQLQueryLaunchArgs) {
const response = await this.get('launches', { flight_number: id });
return this.launchReducer(response[0]);
}

launchReducer(launch: any): GQLLaunch {
return {
id: String(launch.flight_number) || '0',
site: launch.launch_site && launch.launch_site.site_name,
mission: {
name: launch.mission_name,
missionPatchSmall: launch.links.mission_patch_small,
missionPatchLarge: launch.links.mission_patch,
},
};
}
}

export { LaunchesAPI };

现在,因为我使用 GQLLaunch 输入 launchReducer() 的结果,所以 mission 属性类型为 GQLMission 并且此类型只有两个属性,namemissionPatch。它没有 missionPatchSmallmissionPatchLarge,因此我收到此错误:

Type '{ name: any; missionPatchSmall: any; missionPatchLarge: any; }' is not assignable to type 'GQLMission'. Object literal may only specify known properties, and 'missionPatchSmall' does not exist in type 'GQLMission'. ts(2339)

resolvers.ts 文件尝试读取 mission.missionPatchSmallmission.missionPatchLarge 时,会出现类似的错误,因为它们不这样做。 t 存在于 GQLMission 类型的 mission 对象中:

Property 'missionPatchSmall' does not exist on type 'GQLMission'. ts(2339)

我不知道如何处理这个问题,有建议吗?

最佳答案

您将不属于 GQLMission 一部分的属性放在 mission 上,然后向 GQLMission< 显式键入 mission/。一般来说,您尝试从架构生成类型,但解析器的返回类型与架构指定的类型不匹配。

大多数时候,您面临的挑战是由架构设计中的某些缺陷或解析器实现中的一些黑客行为造成的。

因此,您的选择通常是:

  • 放弃为解析器使用架构生成的类型(这是我最不喜欢的选项。)
  • 更改您的架构以匹配您的解析器返回类型(解决架构缺陷。)
  • 更改您的解析器以匹配您的架构返回类型(解决解析器缺陷。)
  • 更改您的架构和解析器以返回一些新的共享类型(解决架构缺陷并更新新架构的解析器实现。)

假设您打算继续为解析器使用架构生成的类型,我们可以消除选项 1,并考虑将最后三个选项应用于您的情况。

  • 让您的解析器实现正确的类型,并更新您的架构以匹配。这意味着更改架构中的 GQLMission 类型以匹配解析器的返回类型(包括 missionPatchLargemissionPatchSmall 属性)并允许您客户端可以直接通过架构查询来查询其中之一或两者。
  • 将您的架构转换为正确的类型,并更新您的解析器实现以匹配。这意味着摆脱多余的返回属性(missionPatchLargemissionPatchSmall),您当前正在使用这些属性来简化实现,并获取适当的 missionPatch code> 在 missionPatchResolver 子解析器中重新设置值(最好命中缓存以防止性能命中)。
  • 重新考虑架构上 missionPatch 的表示方式。考虑一下missionPatch的性质。这真的是一个非此即彼的情况吗?此解决方案将涉及围绕大小和 missionPatch 更改架构 API 的形状,然后需要将其镜像到您的解析器实现上。
  • 您的操作取决于missionPatch 的性质。我的猜测是最后三个选项之一在这里是有意义的。如果两个 missionPatch 类型实际上是不同的变体,则将 missionPatch 更改为 missionPatches 可能是有意义的,它返回一个 MissionPatch 数组 对象,可以按大小 进行过滤。如果一个是另一个的衍生,那么将它们保留为通过架构公开的单独的 missionPatchmissionPatchSmall 字符串可能是最有意义的。

    编辑:查看您正在使用的 api,很明显这些是可以请求的独立值。没有什么小或大的使命。这些是同一任务的不同尺寸的图像。我的方法可能是将这两个值直接包含在您的架构中,或者包含在嵌套的 missionPatch 属性中,例如

    export type GQLMission = {
    name?: Maybe<Scalars['String']>,

    smallPatchUrl: String,
    largePatchUrl: String,

    # OR

    patch?: MissionPatch,
    };

    export type MissionPatch = {
    smallUrl: String,
    largeUrl: String
    };

    旁注:通过图像自身的值对象类型来表示图像并不罕见,其中可能包括不同大小的图像的 URL 以及有关图像的详细信息,例如长宽比或 native 宽度或高度。

    关于typescript - 如何将 GraphQL 与 TypeScript 和 graphql-code-generator 生成的类型一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58420192/

    29 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com