GraphQL(3):参数类型与参数传递

1 基本参数类型

(1)基本类型:String,Int,Float,Boolean和ID。可以在shema声明的时候直接使用。

(2)[类型]代表数组,例如:[int]代表整型数组

2 参数传递

(1)和js传递参数一样,小括号内定义形参,但是注意:参数需要定义类型。

(2)!(叹号)代表参数不能为空。

复制代码
type Query {
    rollDice(numDice: Int!,numSides: Int):[Int]
}

3 代码实例

新建baseType.js

复制代码
const express = require('express');
const {buildSchema} = require('graphql');
const grapqlHTTP = require('express-graphql').graphqlHTTP;

// 定义schema,查询和类型
const schema = buildSchema(`
    type Query {
        getClassMates(classNo: Int!):[String]
    }
`)

//定义查询对应的处理器
const root ={
    getClassMates({classNo}){
        const obj ={
            31:['张三','李四','王五'],
            61:['张大三','李大四','王大五']
        }
        return obj[classNo];
    }
}

const app = express();
app.use('/graphql', grapqlHTTP({
    schema: schema,
    rootValue: root,
    graphiql: true
}))
app.listen(3000);

使用命令启动测试。

复制代码
node baseType.js

访问地址如下:http://localhost:3000/graphql

接口如下:

下面进行测试

(1)不传参数

结果如下,报错提示缺少必填的参数。

(2)传递空值

结果如下,提示该函数类型为int型

(3)传递真实参数

4 自定义参数

GraphQL允许用户自定义参数类型,通常用来描述要获取的资源的属性。

代码如下:

复制代码
const express = require('express');
const {buildSchema} = require('graphql');
const grapqlHTTP = require('express-graphql').graphqlHTTP;
// 定义schema,查询和类型
const schema = buildSchema(`
    type Account {
        name: String
        age: Int
        sex: String
        department: String
        salary(city: String): Int
    }
    type Query {
        getClassMates(classNo: Int!): [String]
        account(username: String): Account
    }
`)
// 定义查询对应的处理器
const root = {
    getClassMates({ classNo}) {
        const obj = {
            31: ['张三', '李四', '王五'],
            61: ['张大三', '李大四', '王大五']
        }
        return obj[classNo];
    },
    account({ username}) {
        const name = username;
        const sex = 'man';
        const age = 18;
        const department = '开发部';
        const salary = ({city}) => {
            if(city === "北京" || city == "上海" || city == "广州" || city == "深圳") {
                return 10000;
            }
            return 3000;
        }
        return {
            name,
            sex,
            age,
            department,
            salary
        }
    }
}

const app = express();

app.use('/graphql', grapqlHTTP({
    schema: schema,
    rootValue: root,
    graphiql: true
}))

// 公开文件夹,供用户访问静态资源
app.use(express.static('public'))

app.listen(3000);

结果如下:

不传递salary参数时候,如下:

传递salary参数时候,如下:

相关推荐
EnCi Zheng1 小时前
SpringBoot 配置文件完全指南-从入门到精通
java·spring boot·后端
烙印6011 小时前
Spring容器的心脏:深度解析refresh()方法(上)
java·后端·spring
Lisonseekpan2 小时前
Guava Cache 高性能本地缓存库详解与使用案例
java·spring boot·后端·缓存·guava
3 小时前
JUC专题 - 并发编程带来的安全性挑战之同步锁
后端
凯哥19703 小时前
迁移PostgreSQL数据库教程
后端
Ray663 小时前
单例模式
后端
用户8356290780513 小时前
掌控PDF页面:使用Python轻松实现添加与删除
后端·python
无责任此方_修行中3 小时前
谁动了我的数据?一个 Bug 背后的“一行代码”真凶
后端·node.js·debug
用户47949283569153 小时前
面试官:讲讲2FA 双因素认证原理
前端·后端·安全
疯狂的程序猴3 小时前
移动端H5网页远程调试:WEINRE、Charles与Genymotion完整指南
后端