欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

graphQL技术Express实施

程序员文章站 2022-05-16 09:14:00
...

GraphQL is a data query language and runtime designed and used at Facebook to request and deliver data to mobile and web apps since 2012.

GraphQL 是一种数据查询语言,自 2012 年以来,由 Facebook 设计和使用,用于请求和向移动和网络应用交付数据。

GraphQL is an open source tool with 12.1K GitHub stars and 799 GitHub forks.

GraphQL 是一个开源工具,具有 12.1K GitHub 星粉 和 799 GitHub 分叉。

官方网址: https://graphql.org/

graphQL技术Express实施
graphQL技术Express实施

curl命令调用:

 

curl -X POST \
-H "Content-Type: application/json" \
-d '{"query": "{ hello }"}' \
http://fe.quxiaoyuan.com:9000/graphql
前端JS调用:

 

fetch('/graphql', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json',
  },
  body: JSON.stringify({query: "{ hello }"})
})
  .then(r => r.json())
  .then(data => console.log('data returned:', data));

var dice = 3;
var sides = 6;
var query = `query RollDice($dice: Int!, $sides: Int) { rollDice(numDice: $dice, numSides: $sides) }`;

fetch('/graphql', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json',
  },
  body: JSON.stringify({
    query,
    variables: { dice, sides },
  })
})
  .then(r => r.json())
  .then(data => console.log('data returned:', data));
 

var dice = 3;
var sides = 6;
var query = `query RollDice($dice: Int!, $sides: Int) { rollDice(numDice: $dice, numSides: $sides) }`;

fetch('/graphql', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json',
  },
  body: JSON.stringify({
    query,
    variables: { dice, sides },
  })
})
  .then(r => r.json())
  .then(data => console.log('data returned:', data));


 

var author = 'andy';
var content = 'hope is a good thing';
var query = `mutation CreateMessage($input: MessageInput) { createMessage(input: $input) { id } }`;

fetch('/graphql', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json',
  },
  body: JSON.stringify({
    query,
    variables: {
      input: {
        author,
        content,
      }
    }
  })
})
  .then(r => r.json())
  .then(data => console.log('data returned:', data));```