gpt4 book ai didi

graphql - 如何使用模式语言创建泛型?

转载 作者:行者123 更新时间:2023-12-04 00:04:27 28 4
gpt4 key购买 nike

使用 facebook 的引用库,我找到了一种破解泛型类型的方法,如下所示:

type PagedResource<Query, Item> = (pagedQuery: PagedQuery<Query>) => PagedResponse<Item>

interface PagedQuery<Query> {
query: Query;
take: number;
skip: number;
}

interface PagedResponse<Item> {
items: Array<Item>;
total: number;
}
function pagedResource({type, resolve, args}) {
return {
type: pagedType(type),
args: Object.assign(args, {
page: { type: new GraphQLNonNull(pageQueryType()) }
}),
resolve
};
function pageQueryType() {
return new GraphQLInputObjectType({
name: 'PageQuery',
fields: {
skip: { type: new GraphQLNonNull(GraphQLInt) },
take: { type: new GraphQLNonNull(GraphQLInt) }
}
});
}
function pagedType(type) {
return new GraphQLObjectType({
name: 'Paged' + type.toString(),
fields: {
items: { type: new GraphQLNonNull(new GraphQLList(type)) },
total: { type: new GraphQLNonNull(GraphQLInt) }
}
});
}
}

但我喜欢 Apollo Server 如何以声明方式创建模式。所以问题是,你们如何使用模式语言创建类似泛型的类型?

最佳答案

您可以创建一个接口(interface)或联合来实现类似的结果。我认为 this article很好地解释了如何正确实现接口(interface)和联合。您的架构看起来像这样:

type Query {
pagedQuery(page: PageInput!): PagedResult
}

input PageInput {
skip: Int!
take: Int!
}

type PagedResult {
items: [Pageable!]!
total: Int
}

# Regular type definitions for Bar, Foo, Baz types...

union Pageable = Bar | Foo | Baz

您还需要为联合定义一个 resolveType 方法。与 graphql-tools ,这是通过解析器完成的:
const resolvers = {
Query: { ... },
Pageable {
__resolveType: (obj) => {
// resolve logic here, needs to return a string specifying type
// i.e. if (obj.__typename == 'Foo') return 'Foo'
}
}
}
__resolveType将要解析的业务对象作为其第一个参数(通常是您给 GraphQL 解析的原始数据库结果)。您需要在此处应用一些逻辑来找出所有不同的 Pageable 类型,即我们正在处理的类型。对于大多数 ORM,您只需添加某种 typename字段添加到您正在使用的模型实例中,并且只有 resolveType归还。

编辑:正如您所指出的,这种方法的缺点是 items 中返回的类型对客户端不再透明——客户端必须知道返回的类型并指定 items 的字段。在像 ... on Foo 这样的内联片段中.当然,您的客户仍然需要对返回的类型有所了解,否则他们将不知道要请求哪些字段。

我想在以声明方式生成模式时,不可能以您想要的方式创建泛型。要使您的模式以与当前相同的方式工作,您必须硬着头皮定义 PagedFoo。当你定义 Foo , 定义 PagedBar当你定义 Bar等等。

我能想到的唯一其他选择是将这两种方法结合起来。以编程方式创建您的“基础”架构。您只需要使用您的 pagedResource 在根查询下定义分页查询。功能。然后您可以使用 printSchema来自 graphql/utilities将其转换为可以与其余类型定义连接的字符串。在您的类型定义中,您可以使用 extend关键字构建在基本模式中已声明的任何类型上,如下所示:
extend Query {
nonPaginatedQuery: Result
}

如果你走这条路,你可以跳过 resolve函数到 pagedResource , 或在您的程序定义类型上定义任何解析器,只需使用您通常传递给 buildExecutableSchema 的解析器对象.

关于graphql - 如何使用模式语言创建泛型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45521040/

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