GraphQL

GraphQL

官网

一种用于 API 的查询语言

诞生原因

遭遇问题

  1. 兼容多平台导致字段冗余
  2. 一个页面需要多次调用 API 聚合数据
  3. 需求经常改动导致接口很难为单一接口精简逻辑

解决思路

把静态的接口变成动态

使用例子

安装包

npm install --save -D express express-graphql graphql

schema.js

//schema.js
const {
      GraphQLSchema,
      GraphQLObjectType,
      GraphQLString,
    } = require('graphql');
const queryObj = new GraphQLObjectType({
    name: 'myFirstQuery',
    description: 'a hello world demo',
    fields: {
        hello: {
            name: 'a hello world query',
            description: 'a hello world demo',
            type: GraphQLString,
            resolve(parentValue, args, request) {
                return 'hello world !';
            }
        }
    }
});
module.exports = new GraphQLSchema({
  query: queryObj
});

sever.js

// server.js
const express = require('express');
const expressGraphql = require('express-graphql');
const app = express();

const schema = require('./schema');
app.use('/graphql', expressGraphql({
	schema,
	graphiql: true
}));

app.get('/', (req, res) => res.end('index'));

app.listen(8000, (err) => {
  if(err) {throw new Error(err);}
  console.log('*** server started ***');
});

查询操作

{
  hello
}

Apollo

Apollo 是实现,GraphQL 是标准,和 JS/ECMA 的关系一样。

Relay Modern

Relay是一套基于GraphQL和React的框架,它将这两者结合,在原来React组件的基础上,进一步将请求封装进组件。
官方提供了一个TodoMVC的demo可以参考,基本涵盖了CRUD操作。

你可能感兴趣的:(前端)