要使用Apollo GraphQL的makeExecutableSchema和playground,您需要先安装相关软件包。以下是一种解决方法,包含了代码示例:
npm install apollo-server graphql
index.js
,并将以下代码复制到该文件中:const { ApolloServer, gql } = require('apollo-server');
const { makeExecutableSchema } = require('graphql-tools');
// 定义类型定义
const typeDefs = gql`
type Query {
hello: String
}
`;
// 定义解析器
const resolvers = {
Query: {
hello: () => 'Hello, world!',
},
};
// 创建可执行的GraphQL模式
const schema = makeExecutableSchema({
typeDefs,
resolvers,
});
// 创建Apollo服务器
const server = new ApolloServer({ schema });
// 启动服务器并在localhost:4000上运行Playground
server.listen(4000).then(({ url }) => {
console.log(`Server running at ${url}`);
});
node index.js
打开浏览器并访问http://localhost:4000
,您将看到Apollo Playground的界面。
在左侧的编辑器中,尝试运行以下GraphQL查询:
query {
hello
}
{
"data": {
"hello": "Hello, world!"
}
}
这就是使用Apollo GraphQL的makeExecutableSchema和playground的基本解决方法。您可以根据自己的需求扩展和修改类型定义和解析器。