快速上手使用express-graphql 构建graphql 查询接口 本文共有3201个字,关键词:graphql、express、express-graphql 直接上代码 ``` const express = require('express') const {buildSchema} = require('graphql') const {graphqlHTTP} = require('express-graphql') const schema = buildSchema(` type Student{ name:String sex:String age:Int is_test: Boolean otherInfo(type:String):String } type Query{ getClassInfo(classNo: Int!):[String] getStudents(classNo: Int!):Student } `) const root = { //需要返回[String] 字符串数组类型 getClassInfo({classNo}){ const obj = { 1:["A","B","C"], 2:["F","G","H"] } return obj[classNo] }, getStudents({classNo}){ const obj={ 1:{"name":"张三","age":18,"sex":"男","is_test":true,"otherInfo":""}, 2:{"name":"李四","age":88,"sex":"女","is_test":false,"otherInfo":""} } const otherInfo = ({type}) => { if(type == "new"){ return "新班级"; } else{ return "旧班级" } } const newobj = obj[classNo] newobj.otherInfo = otherInfo return newobj } } const app = express(); app.use('/g',graphqlHTTP({ schema: schema, rootValue: root, graphiql: true //是否调试模式,dev模式下开启 })) app.listen(3000); ``` 保存为test.js 初如化package.json ``` cnpm init -y ``` 安装依赖包 ``` cnpm i express-graphql graphql express -S ``` 运行项目: ``` node test.js ``` 重点说明: 1、graphqlHTTP 需要传入三个参数, 2、schema和root 中的方法 一一对应。 3、Int! 加叹号为必传值 4、Student 结构 为自定义数据类型 5、otherInfo 带参,对应需要定义箭头函数 测试查询地址: ``` http://localhost:3000/g?query=%23%20Welcome%20to%20GraphiQL%0A%23%0A%23%20GraphiQL%20is%20an%20in-browser%20tool%20for%20writing%2C%20validating%2C%20and%0A%23%20testing%20GraphQL%20queries.%0A%23%0A%23%20Type%20queries%20into%20this%20side%20of%20the%20screen%2C%20and%20you%20will%20see%20intelligent%0A%23%20typeaheads%20aware%20of%20the%20current%20GraphQL%20type%20schema%20and%20live%20syntax%20and%0A%23%20validation%20errors%20highlighted%20within%20the%20text.%0A%23%0A%23%20GraphQL%20queries%20typically%20start%20with%20a%20%22%7B%22%20character.%20Lines%20that%20start%0A%23%20with%20a%20%23%20are%20ignored.%0A%23%0A%23%20An%20example%20GraphQL%20query%20might%20look%20like%3A%0A%23%0A%23%20%20%20%20%20%7B%0A%23%20%20%20%20%20%20%20field(arg%3A%20%22value%22)%20%7B%0A%23%20%20%20%20%20%20%20%20%20subField%0A%23%20%20%20%20%20%20%20%7D%0A%23%20%20%20%20%20%7D%0A%23%0A%23%20Keyboard%20shortcuts%3A%0A%23%0A%23%20%20Prettify%20Query%3A%20%20Shift-Ctrl-P%20(or%20press%20the%20prettify%20button%20above)%0A%23%0A%23%20%20%20%20%20Merge%20Query%3A%20%20Shift-Ctrl-M%20(or%20press%20the%20merge%20button%20above)%0A%23%0A%23%20%20%20%20%20%20%20Run%20Query%3A%20%20Ctrl-Enter%20(or%20press%20the%20play%20button%20above)%0A%23%0A%23%20%20%20Auto%20Complete%3A%20%20Ctrl-Space%20(or%20just%20start%20typing)%0A%23%0A%0Aquery%7B%0A%20%20getClassInfo(classNo%3A1)%0A%20%20getStudents(classNo%3A1)%20%7B%0A%20%20%20%20name%0A%20%20%20%20sex%0A%20%20%20%20age%0A%20%20%20%20is_test%0A%20%20%20%20otherInfo(type%3A%22new%22)%0A%20%20%7D%0A%7D ``` × yihong (๑>ڡ<)☆谢谢老板~ 2元 5元 10元 50元 100元 任意金额 2元 使用微信扫描二维码完成支付 版权声明:本文为作者原创,如需转载须联系作者本人同意,未经作者本人同意不得擅自转载。 码农心得 2021-09-01 评论 1650 次浏览