GraphQL
一种api文档查询语言
基本语法
本地运行
git clone https://github.com/apollographql/starwars-server
cd starwars-server
npm install
npm start
执行上面的命令之后打开下面的地址 即可学习
http://localhost:8080/graphql
简单查询
要求返回什么就返回什么
{
  hero{
    friends{
      name
    }
  }
}{
  "data": {
    "hero": {
      "friends": [
        {
          "name": "Luke Skywalker"
        },
        {
          "name": "Han Solo"
        },
        {
          "name": "Leia Organa"
        }
      ]
    }
  }
}带参数进行筛选
{
  human(id:1000){
    name
  }
}结果
{
  "data": {
    "human": {
      "name": "Luke Skywalker"
    }
  }
}取别名
防止冲突
{
  A:hero(episode:EMPIRE){
    name
  }
  B:hero(episode:JEDI){
    name
  }
}{
  "data": {
    "A": {
      "name": "Luke Skywalker"
    },
    "B": {
      "name": "R2-D2"
    }
  }
}复用查询的片段
{
  A:hero(episode:EMPIRE){
   ... heros
  }
  B:hero(episode:JEDI){
   ... heros 
  }
}
fragment heros on Character {
  name
  appearsIn
  friends{
    name
  }
}当查询的参数来自于用户输入的时候
query HeroNameAndFriends($episode: Episode){
  A:hero(episode:$episode){
    name
    friends{
      name
    }
  }
}设置参数的默认值
query HeroNameAndFriends($episode: Episode! = JEDI ){
  A:hero(episode:$episode){
    name
    friends{
      name
    }
  }
}修改数据
mutation{
  createReview(episode:JEDI,review:{stars:3}){
    episode
    stars
  }
}用内联片段查询具体类型
query HeroNameAndFriends($ep: Episode){
  hero(episode: $ep){
    name
    ... on Droid{
      primaryFunction
    }
  }
}{
  search(text:"an"){
    __typename
    ... on Human{
      name
      height
    }
    ... on Starship{
      name
      length
    }
  }
}编辑js并且运行
js内容
const express = require('express');
const { buildSchema } =require('graphql');
const { graphqlHTTP } = require("express-graphql");
//定义schema 查询和类型
const schema = buildSchema(
    `
    type Query {
        hello: String
    }
`)
//定义查询对应的处理器
const root = {
    hello: () =>{
        return 'hello world';
    }
}
const app =express();
app.use("/graphql",graphqlHTTP({
    schema: schema,
    rootValue: root,
    graphiql: true 
}))
app.listen(3000);
运行命令
npm init -y
npm install experss graphql express-graphql -S
node helloWorld.js
通过端口找到在上面运行的进程 然后结束进程
找到8080端口 第二行最后的数字为process ID 即PID,
netstat -o -n -a | findstr :8080
TCP    0.0.0.0:3000      0.0.0.0:0              LISTENING       3116拿到pid 直接可以结束进程
taskkill /F /PID 3116
 
 
 
 
 
 