Apollo Server能与GraphQL Tools的stitchSchemas一起使用吗?
创始人
2024-09-09 05:30:35
0

是的,Apollo Server可以与GraphQL Tools的stitchSchemas一起使用。stitchSchemas是GraphQL Tools库中的一个功能,用于将多个GraphQL模式合并成一个模式。

下面是一个使用Apollo Server和stitchSchemas的示例代码:

首先,安装所需的依赖项:

npm install apollo-server graphql-tools

然后,创建一个包含各个GraphQL模式的文件,例如schema1.jsschema2.js

// schema1.js
const { makeExecutableSchema } = require('graphql-tools');

const typeDefs = `
  type Query {
    hello: String
  }
`;

const resolvers = {
  Query: {
    hello: () => 'Hello from schema 1!'
  }
};

module.exports = makeExecutableSchema({ typeDefs, resolvers });
// schema2.js
const { makeExecutableSchema } = require('graphql-tools');

const typeDefs = `
  type Query {
    goodbye: String
  }
`;

const resolvers = {
  Query: {
    goodbye: () => 'Goodbye from schema 2!'
  }
};

module.exports = makeExecutableSchema({ typeDefs, resolvers });

接下来,创建一个Apollo Server实例,并使用stitchSchemas合并这些模式:

const { ApolloServer } = require('apollo-server');
const { stitchSchemas } = require('@graphql-tools/stitch');

const schema1 = require('./schema1');
const schema2 = require('./schema2');

const mergedSchema = stitchSchemas({
  schemas: [schema1, schema2]
});

const server = new ApolloServer({ schema: mergedSchema });

server.listen().then(({ url }) => {
  console.log(`Server ready at ${url}`);
});

现在,你可以启动Apollo Server,并通过浏览器或其他客户端访问GraphQL API。API中将包含从两个模式中定义的查询和解析器函数。

这是一个示例查询:

query {
  hello
  goodbye
}

返回的结果应该是:

{
  "data": {
    "hello": "Hello from schema 1!",
    "goodbye": "Goodbye from schema 2!"
  }
}

通过使用Apollo Server和stitchSchemas,你可以轻松地将多个GraphQL模式组合成一个统一的API。

相关内容

热门资讯

安装apache-beam==... 出现此错误可能是因为用户的Python版本太低,而apache-beam==2.34.0需要更高的P...
避免在粘贴双引号时向VS 20... 在粘贴双引号时向VS 2022添加反斜杠的问题通常是由于编辑器的自动转义功能引起的。为了避免这个问题...
Android Recycle... 要在Android RecyclerView中实现滑动卡片效果,可以按照以下步骤进行操作:首先,在项...
omi系统和安卓系统哪个好,揭... OMI系统和安卓系统哪个好?这个问题就像是在问“苹果和橘子哪个更甜”,每个人都有自己的答案。今天,我...
原生ios和安卓系统,原生对比... 亲爱的读者们,你是否曾好奇过,为什么你的iPhone和安卓手机在操作体验上有着天壤之别?今天,就让我...
Android - 无法确定任... 这个错误通常发生在Android项目中,表示编译Debug版本的Java代码时出现了依赖关系问题。下...
Android - NDK 预... 在Android NDK的构建过程中,LOCAL_SRC_FILES只能包含一个项目。如果需要在ND...
Akka生成Actor问题 在Akka框架中,可以使用ActorSystem对象生成Actor。但是,当我们在Actor类中尝试...
Agora-RTC-React... 出现这个错误原因是因为在 React 组件中使用,import AgoraRTC from “ago...
Alertmanager在pr... 首先,在Prometheus配置文件中,确保Alertmanager URL已正确配置。例如:ale...