API 参考文档:@apollo/subgraph
本 API 参考文档记录了来自@apollo/subgraph
软件包的导出。此软件包使您能够将Apollo Server用作子图在联合超边图中的子图。有关更多信息,请参阅使用 Apollo Server 实施子图。
注意,我们建议使用 @apollo/subgraph
与 Apollo Server 一起使用,但它是与基于 graphql-js
构建的任何 GraphQL 服务器兼容的。
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
。
该函数接受以下参数。
参数
名称 类型 | 描述 |
---|---|
| 从其他 子图传递过来的 实体 的表示。 此对象包含一个 |
| 传递给执行特定 操作 的每个 解析器 的对象,从而使得解析器可以共享有用的上下文。 在 解析器 和插件中,此对象的名称为 |
| 包含关于操作执行状态的 操作 的信息,包括字段名称、从根到字段的路径等。 此对象的核 字段 已列在 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` herereturn 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` herereturn dataSources.users.fetchUserById(user.id);},},};