实现GraphQL解析器函数有多种方法,这里将介绍两种常用的解决方法。
方法一:使用GraphQL.js库
npm install graphql
const { graphql, buildSchema } = require('graphql');
// 定义GraphQL schema
const schema = buildSchema(`
type Query {
hello: String
}
`);
// 定义解析器函数
const root = {
hello: () => {
return 'Hello, world!';
},
};
// 执行GraphQL查询
const query = '{ hello }';
graphql(schema, query, root).then((response) => {
console.log(response.data);
});
方法二:使用Apollo Server
npm install apollo-server
const { ApolloServer, gql } = require('apollo-server');
// 定义GraphQL schema
const typeDefs = gql`
type Query {
hello: String
}
`;
// 定义解析器函数
const resolvers = {
Query: {
hello: () => {
return 'Hello, world!';
},
},
};
// 创建Apollo Server实例
const server = new ApolloServer({ typeDefs, resolvers });
// 启动服务器
server.listen().then(({ url }) => {
console.log(`Server listening at ${url}`);
});
这些示例代码均展示了如何实现一个简单的GraphQL解析器函数,其中解析器函数根据查询返回了一个字符串 "Hello, world!"。你可以根据自己的需求来定义更复杂的解析器函数。