Resolver是一组函数,可为GraphQL查询生成响应.简单来说,解析器充当GraphQL查询处理程序. GraphQL架构中的每个解析器函数都接受下面给出的四个位置参数 :
fieldName:(root, args, context, info) => { result }
解析器函数的示例如下所示 :
//resolver function with no parameters and returning string greeting:() => { return "hello from TutorialsPoint !!!" } //resolver function with no parameters and returning list students:() => db.students.list() //resolver function with arguments and returning object studentById:(root,args,context,info) => { return db.students.get(args.id); }
以下是位置参数及其描述 :
Sr.No. | 参数&说明 |
---|---|
1 | root 包含从父字段上的解析程序返回的结果的对象. |
2 | args 将参数传递给查询字段的对象. |
3 | context 这是特定查询中所有解析器共享的对象. |
4 | info 它包含有关查询执行状态的信息,包括字段名称,从根开始的字段路径. |
GraphQL中的解析器可以返回不同类型的值,如下面给出的 : 去;
Sr.No. | 参数和描述 |
---|---|
1 | null或undefined 这表示无法找到对象 |
2 | 数组 这仅在架构指示字段的结果应该是列表时有效 |
3 | 承诺 解析器经常做异步操作,如从数据库或后端API获取,因此可以返回promises |
4 | 标量或对象 解析器也可以返回其他值 |
让我们创建一个简单的应用程序来理解解析器.这将创建用于通过服务器的id查询学生的模式.学生数据将存储在一个平面文件中,我们将使用名为 notarealdb 的节点模块伪造数据库并从平面文件中读取.
以下是创建简单应用程序的逐步过程 :
创建名为 resolver-app 的文件夹.从终端将目录更改为 resolver-app .稍后,请按照环境设置章节中的步骤3到5进行操作.
在项目文件夹resolver-app中添加schema.graphql文件并添加以下代码 :
type Query { greeting:String students:[Student] studentById(id:ID!):Student } type Student { id:ID! firstName:String lastName:String password:String collegeId:String }
模式文件显示用户可以查询问候语,学生和 studentById .要检索具有特定ID的学生,我们使用数据类型ID!,其中显示了一个不可为空的唯一标识符字段. 学生字段返回一组学生,问候语返回一个简单的字符串值.
在项目文件夹中创建文件 resolvers.js 并添加以下代码 :
const db = require('./db') const Query = { //resolver function for greeting greeting:() => { return "hello from TutorialsPoint !!!" }, //resolver function for students returns list students:() => db.students.list(), //resolver function for studentbyId studentById:(root,args,context,info) => { //args will contain parameter passed in query return db.students.get(args.id); } } module.exports = {Query}
此处, studentById 需要在三个参数.如本章所述,可以从args中检索 studentId ; root将包含Query对象本身.要返回一个特定的学生,我们需要在学生集合中调用带有id参数的get方法.
这里 greeting,students,studentById 是处理这个问题的解析器查询. 学生解析器功能从数据访问层返回学生列表.要访问模块外部的解析器函数,必须使用module.exports导出Query对象.
创建server.js文件.请参阅环境设置章节中的步骤8.在终端中执行命令npm start.服务器将在9000端口上启动并运行.在这里,我们使用GraphiQL作为客户端来测试应用程序.
打开浏览器并输入URL, http://localhost:9000/graphiql .在编辑器中输入以下查询 :
{ studentById(id:"S1001") { id firstName lastName } }
上述查询的输出如下所示 :
{ "data": { "studentById": { "id": "S1001", "firstName": "Mohtashim", "lastName": "Mohammad" } } }