参数类型与参数传递

2020-07-16  本文已影响0人  紫雨杰

一、基本参数类型

1、基本类型: String,Int,Float,Boolean和ID 五个。可以在schema声明的时候直接使用;
2、[类型] 代表数组, 例如: [Int] 代表整型数组

二、参数传递

1、和js传递参数一样,小括号内定义形参,但是注意:参数需要定义类型;
2、!(叹号) 代表参数不能为空;
例如:
type Query {
//hello方法中有两个参数name和age,name类型为String, age类型为Int, 并且age不能为空,返回值为整型数组
hello(name: String, age: Int! ) : [Int]
}

三、自定义参数类型

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

const express = require('express');
const {buildSchema} = require('graphql');
const {graphqlHTTP} = require('express-graphql');


// 定义Schema,  查询方法和返回值类型
const schema = buildSchema(`

  // Account 为自定义类型
  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 = {
            11: ['张三', '李四', '王五'],
            12: ['张飞', '曹操', '关羽']
        }
        return obj[classNo];
    },
    account({username}) {
        const name = username;
        const age = 12;
        const sex = '男';
        const department = '测试部';
        const salary = ({city}) => {
            if (city == '北京' || city == '上海' || city == '广州') {
                return 10000;
            }
            return 4000;
        }
        return {
            name, 
            age, 
            sex, 
            department, 
            salary  
        }
    }
}

const app = express();

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

app.listen(3000);
image.png
上一篇 下一篇

猜你喜欢

热点阅读