GraphQL的使用

198 阅读3分钟

简介

GraphQL 既是一种用于 API 的查询语言也是一个满足你数据查询的运行时。 GraphQL 对你的 API 中的数据提供了一套易于理解的完整描述,使得客户端能够准确地获得它需要的数据,而且没有任何冗余,也让 API 更容易地随着时间推移而演进,还能用于构建强大的开发者工具。

安装使用

安装依赖

npm install graphql apollo-server-express express -S

内置类型

1.查询和变更类型

作为客户端访问的入口,这两个类型本质上也是对象类型

Query

Mutation

2.标量类型

标量类型用于表示基本的字段数据,表示查询数据的叶子节点

Int

Float

String

Boolean

ID :唯一标识符

3.枚举类型

枚举类型是一种特殊的标量,它限制在一个特殊的可选值集合内

enum

enum hobby{swiming,coding,singing} //对象里的值只能获取三种值之一,其他类型的值不可以

4.列表和非空

[]

!

type Student {
    name: String!      //表示name不能为空字符串
    scores:[Course!]!  //数组不能为空,Course包含的成员也不能为空
}

5.输入类型

参数也可以是复杂类型,主要用于变更 Mutation场景(需要客户端传递输入类型)

//定义数据类型
const typeDefs = gql `
  # 输入类型
  input UserInfo{
    uname: String
    pwd:String
  }
  # 用户类型 
  type User  {
    id:ID
    uname:String
    pwd:String 
  }
  # 变更类型
  type Mutation {
    addUserByInput(userInput:UserInfo): User
  }
  # 查询类型
  type Query {
    hello: String
  }
`;
//解析数据类型对应的具体数据
const resolvers = {
  Query: {
    hello: () => 'Hello world!',
  },
  Mutation:{
    addUserByInput:(obj,args)=>{
      let {userInput:{uname,pwd}}=args
      return {
        id:123,
        uname,
        pwd
      }
    }
  }
};


//客户端
mutation{
	addUserByInput(userInput:{
    uname:"张三",
    pwd:"12345"
  }){
    id
    uname
    pwd
  }
}

数据源的使用

//导入相关依赖
const express = require('express');
const {ApolloServer,gql} = require('apollo-server-express');
const db = require('./db.js')
//定义数据类型
const typeDefs = gql `
type Student {
  sname:String
  age:Int
}
  # 查询类型
  type Query {
    hello: [Student!]!
  }
`;
//解析数据类型对应的具体数据
const resolvers = {
  Query: {
    hello: async (parent,args,context) => {
      let res = await context.db.getData()
      let obj = JSON.parse(res)
      return obj;
    },
  },
};

const context = () => {
  return {
    db:db
  }
}
//整合apollo-server和express
const server = new ApolloServer({typeDefs,resolvers,context});
const app = express();
server.applyMiddleware({app});

//启动监听
app.listen({port: 4000}, () =>
  console.log('Now browse to http://localhost:4000' + server.graphqlPath)
);



//客户端
{
  hello{
    sname
    age
  }
}

服务端使用

基本使用

//导入相关依赖
const express = require('express');
const {ApolloServer,gql} = require('apollo-server-express');
//定义数据类型
const typeDefs = gql `
  #分数
  type Course {
    cname:String
    score:Float
  }
  #学生
  type Student {
    sname:String
    scores:[Course]
  }
  type Query {
    hello: String
    stu: Student
  }
`;
//解析数据类型对应的具体数据
const resolvers = {
  Query: {
    hello: () => 'Hello world!',
    stu:()=>{
      return {sname:'张三',scores:[{cname:'数学',score:85},{cname:'语文',score:95}]
      }
    }
  },
};
//整合apollo-server和express
const server = new ApolloServer({typeDefs,resolvers});
const app = express();
server.applyMiddleware({app});

//启动监听
app.listen({port: 4000}, () =>
  console.log('Now browse to http://localhost:4000' + server.graphqlPath)
);


#请求
{
  stu{
    sname
    scores{
      cname
      score
    }
  }
}

基本参数

//定义类型接参
type Query {
    hello: String
    stu(num:Int): Student
}

//返回数据接参
stu:(obj,args)=>{
   args.num
}

//查询传参
{
  stu(num:2){
    sname
    scores{
      cname
      score
    }
  }
}

VUE版实例

//导入相关依赖
const express = require('express');
const {ApolloServer,gql} = require('apollo-server-express');
const comment = require('./data-file')
const weather = require('./data-api')
const link = require('./data-db')
//定义数据类型
const typeDefs = gql `
input CommentInput{
  username:String
  content:String
}
type Comment {
  username: String
  content: String 
  date: String
}
type Link {
  lname: String
  lurl:String
}
type Weather {
  wea: String
  temp:String
}
type Data {
  list:[Comment]
  link:[Link]
  weather:Weather
}
type Query {
  info:Data
}
type Mutation {
  createComment(commentInput:CommentInput):Comment
}
`;
//解析数据类型对应的具体数据
const resolvers = {
  Query: {
    info: async (parent,args,context) => {
      let ret = await context.comment.getData()
      let list = JSON.parse(ret)
       
      let link = await context.link.getData()
      let weather = await context.weather.getData()

      return {
        list,
        link,
        weather
      }

    }
  },
  Mutation:{
    createComment:async (parent,args,context)=>{
      let ret = await context.comment.setData(args.commentInput.username,args.commentInput.content)
      if (ret === "success") {
        return {
          username:args.commentInput.username,
          content: args.commentInput.content
        }
      }
    }
  }
};

const context = () => {
  return {
    comment,
    weather,
    link
  }
}
//整合apollo-server和express
const server = new ApolloServer({typeDefs,resolvers,context});
const app = express();
server.applyMiddleware({app});

//启动监听
app.listen({port: 4000}, () =>
  console.log('Now browse to http://localhost:4000' + server.graphqlPath)
);