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