- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在关注 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
并且此类型只有两个属性,name
和 missionPatch
。它没有 missionPatchSmall
或 missionPatchLarge
,因此我收到此错误:
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.missionPatchSmall
或 mission.missionPatchLarge
时,会出现类似的错误,因为它们不这样做。 t 存在于 GQLMission
类型的 mission
对象中:
Property 'missionPatchSmall' does not exist on type 'GQLMission'. ts(2339)
我不知道如何处理这个问题,有建议吗?
最佳答案
您将不属于 GQLMission
一部分的属性放在 mission
上,然后向 GQLMission< 显式键入
。一般来说,您尝试从架构生成类型,但解析器的返回类型与架构指定的类型不匹配。mission
/
大多数时候,您面临的挑战是由架构设计中的某些缺陷或解析器实现中的一些黑客行为造成的。
因此,您的选择通常是:
假设您打算继续为解析器使用架构生成的类型,我们可以消除选项 1,并考虑将最后三个选项应用于您的情况。
GQLMission
类型以匹配解析器的返回类型(包括 missionPatchLarge
和 missionPatchSmall
属性)并允许您客户端可以直接通过架构查询来查询其中之一或两者。missionPatchLarge
和 missionPatchSmall
),您当前正在使用这些属性来简化实现,并获取适当的 missionPatch
code> 在 missionPatchResolver
子解析器中重新设置值(最好命中缓存以防止性能命中)。missionPatch
的表示方式。考虑一下missionPatch
的性质。这真的是一个非此即彼的情况吗?此解决方案将涉及围绕大小和 missionPatch
更改架构 API 的形状,然后需要将其镜像到您的解析器实现上。您的操作取决于missionPatch
的性质。我的猜测是最后三个选项之一在这里是有意义的。如果两个 missionPatch
类型实际上是不同的变体,则将 missionPatch
更改为 missionPatches
可能是有意义的,它返回一个 MissionPatch 数组
对象,可以按大小
进行过滤。如果一个是另一个的衍生,那么将它们保留为通过架构公开的单独的 missionPatch
和 missionPatchSmall
字符串可能是最有意义的。
编辑:查看您正在使用的 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/
我正在尝试编写一个相当多态的库。我遇到了一种更容易表现出来却很难说出来的情况。它看起来有点像这样: {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE
谁能解释一下这个表达式是如何工作的? type = type || 'any'; 这是否意味着如果类型未定义则使用“任意”? 最佳答案 如果 type 为“falsy”(即 false,或 undef
我有一个界面,在IAnimal.fs中, namespace Kingdom type IAnimal = abstract member Eat : Food -> unit 以及另一个成功
这个问题在这里已经有了答案: 关闭 10 年前。 Possible Duplicate: What is the difference between (type)value and type(va
在 C# 中,default(Nullable) 之间有区别吗? (或 default(long?) )和 default(long) ? Long只是一个例子,它可以是任何其他struct类型。 最
假设我有一个案例类: case class Foo(num: Int, str: String, bool: Boolean) 现在我还有一个简单的包装器: sealed trait Wrapper[
这个问题在这里已经有了答案: Create C# delegate type with ref parameter at runtime (1 个回答) 关闭 2 年前。 为了即时创建委托(dele
我正在尝试获取图像的 dct。一开始我遇到了错误 The function/feature is not implemented (Odd-size DCT's are not implemented
我正在尝试使用 AFNetworking 的 AFPropertyListRequestOperation,但是当我尝试下载它时,出现错误 预期的内容类型{( “应用程序/x-plist” )}, 得
我在下面收到错误。我知道这段代码的意思,但我不知道界面应该是什么样子: Element implicitly has an 'any' type because index expression is
我尝试将 SignalType 从 ReactiveCocoa 扩展为自定义 ErrorType,代码如下所示 enum MyError: ErrorType { // .. cases }
我无法在任何其他问题中找到答案。假设我有一个抽象父类(super class) Abstract0,它有两个子类 Concrete1 和 Concrete1。我希望能够在 Abstract0 中定义类
我想知道为什么这个索引没有用在 RANGE 类型中,而是用在 INDEX 中: 索引: CREATE INDEX myindex ON orders(order_date); 查询: EXPLAIN
我正在使用 RxJava,现在我尝试通过提供 lambda 来订阅可观察对象: observableProvider.stringForKey(CURRENT_DELETED_ID) .sub
我已经尝试了几乎所有解决问题的方法,其中包括。为 提供类型使用app.use(express.static('public'))还有更多,但我似乎无法为此找到解决方案。 index.js : imp
以下哪个 CSS 选择器更快? input[type="submit"] { /* styles */ } 或 [type="submit"] { /* styles */ } 只是好
我不知道这个设置有什么问题,我在 IDEA 中获得了所有注释(@Controller、@Repository、@Service),它在行号左侧显示 bean,然后转到该 bean。 这是错误: 14-
我听从了建议 registering java function as a callback in C function并且可以使用“简单”类型(例如整数和字符串)进行回调,例如: jstring j
有一些 java 类,加载到 Oracle 数据库(版本 11g)和 pl/sql 函数包装器: create or replace function getDataFromJava( in_uLis
我已经从 David Walsh 的 css 动画回调中获取代码并将其修改为 TypeScript。但是,我收到一个错误,我不知道为什么: interface IBrowserPrefix { [
我是一名优秀的程序员,十分优秀!