加入我们,于10月8日至10日在纽约市了解有关GraphQL联邦和API平台工程的最新的技巧、趋势和新闻。加入我们,在纽约市举行2024年GraphQL峰会
文档
免费开始

API 参考文档:@apollo/subgraph


本 API 参考文档记录了来自@apollo/subgraph软件包的导出。此软件包使您能够将用作在联合中的。有关更多信息,请参阅使用 Apollo Server 实施子图

注意,我们建议使用 @apollo/subgraph与 Apollo Server 一起使用,但它是与基于 graphql-js构建的任何 兼容的。

buildSubgraphSchema

此方法在 @apollo/federation v0.28.0(之前名称仍然有效,但在未来的版本中可能会被删除)之后已重命名为buildFederatedSchema

一个函数,它接收一个模式模块对象(或它们的数组)并返回一个联合就绪的

const server = new ApolloServer({
schema: buildSubgraphSchema({ typeDefs, resolvers }),
});
const server = new ApolloServer({
schema: buildSubgraphSchema({ typeDefs, resolvers }),
});

在用于 定义子图的联邦图中的 时使用。

每个架构模块都是一个具有以下格式的对象

{
typeDefs: DocumentNode,
resolvers: ResolverMap
}

参数

名称
类型
描述
模块

对象数组

必需。 上面的结构所示的一个(或多个)架构模块对象。

示例

import gql from 'graphql-tag';
import { ApolloServer } from '@apollo/server';
import { buildSubgraphSchema } from '@apollo/subgraph';
const typeDefs = gql`
type Query {
me: User
}
type User @key(fields: "id") {
id: ID!
username: String
}
`;
const resolvers = {
Query: {
me() {
return { id: '1', username: '@ava' };
},
},
User: {
__resolveReference(user, { fetchUserById }) {
return fetchUserById(user.id);
},
},
};
const server = new ApolloServer({
schema: buildSubgraphSchema({ typeDefs, resolvers }),
});
import gql from 'graphql-tag';
import { ApolloServer } from '@apollo/server';
import { buildSubgraphSchema } from '@apollo/subgraph';
const typeDefs = gql`
type Query {
me: User
}
type User @key(fields: "id") {
id: ID!
username: String
}
`;
const resolvers = {
Query: {
me() {
return { id: '1', username: '@ava' };
},
},
User: {
__resolveReference(user, { fetchUserById }) {
return fetchUserById(user.id);
},
},
};
const server = new ApolloServer({
schema: buildSubgraphSchema({ typeDefs, resolvers }),
});

__resolveReference

一个特殊 引用解析器 函数的名称,你可以为子图架构中的每个 实体 定义。

__resolveReference 函数允许你的 的查询计划器通过其他 使用以引用实体的任何唯一标识符解析特定 。有关详情,请参阅 定义实体

如果可以解析实体, __resolveReference 返回该实体。否则,返回 null

该函数接受以下参数。

参数

名称
类型
描述
引用

对象

从其他 子图传递过来的 实体 的表示。

此对象包含一个 __typename 字段,以及子图用于实体 @key 的任意字段。

上下文

对象

传递给执行特定 的每个 解析器 的对象,从而使得解析器可以共享有用的上下文。

和插件中,此对象的名称为 contextValue。有关详细信息,请参阅 上下文 参数》

状态信息

对象

包含关于操作执行状态的 操作 的信息,包括字段名称、从根到字段的路径等。

此对象的核 已列在 GraphQL.js 源代码

示例

const typeDefs = gql`
type User @key(fields: "id") {
id: ID!
username: String
}
`;
const resolvers = {
User: {
__resolveReference(user, { dataSources }) {
// user will always have at least the `id` and the `__typename` here
return dataSources.users.fetchUserById(user.id);
},
},
};
const typeDefs = gql`
type User @key(fields: "id") {
id: ID!
username: String
}
`;
const resolvers = {
User: {
__resolveReference(user, { dataSources }) {
// user will always have at least the `id` and the `__typename` here
return dataSources.users.fetchUserById(user.id);
},
},
};
上一页
设置
下一页
设置
评价文章评价在GitHub上编辑编辑论坛Discord

©2024Apollo Graph Inc.,即Apollo GraphQL。

隐私政策

公司