且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

GraphQL:Node.js代码实现简单例子

更新时间:2022-08-22 14:32:32

GraphQL:Node.js代码实现简单例子

GraphQL 是一种针对 Graph(图状数据)进行查询特别有优势的 Query Language(查询语言)


文档:

国内:https://graphql.cn/

国外:https://graphql.org/


一、一个简单的例子

文档:https://graphql.cn/graphql-js/


依赖

npm i --save graphql

示例

var { graphql, buildSchema } = require('graphql');

// 使用 GraphQL schema language 构建一个 schema
var schema = buildSchema(`
  type Query {
    hello: String
  }
`);

// 根节点为每个 API 入口端点提供一个 resolver 函数
var root = {
  hello: () => {
    return 'Hello world!';
  },
};

// 运行 GraphQL query '{ hello }' ,输出响应
graphql(schema, '{ hello }', root).then((response) => {
  console.log(response);
});

二、整合Express提供API服务

依赖

npm i --save express  express-graphql graphql cors axios

服务端 server.js

const express = require("express");
const cors = require("cors"); // 用来解决跨域问题

const { graphqlHTTP } = require("express-graphql");
const { buildSchema } = require("graphql");

// 创建 schema
// 1. 感叹号 ! 代表 not-null
const schema = buildSchema(`
  type Query {
    username: String
    age: Int!
  }
`);


//定义服务端数据
const root = {
  username: () => {
    return "李华";
  },
  age: () => {
    return Math.ceil(Math.random() * 100);
  },
};

const app = express();
app.use(cors());
app.use("/graphql", graphqlHTTP({
    schema: schema,
    rootValue: root,
    graphiql: true,  // 启用GraphiQL
  })
);

app.listen(3300, ()=>{
    console.log("Running a GraphQL API server at http://localhost:3300/graphql");
});

可视化地址:http://localhost:3300/graphql

客户端 client.js

const axios = require("axios");

let data = {
    query: '{username, age}'
}

axios.post("http://localhost:3300/graphql", data).then((res) => {
  console.log(res.data.data);
});
// { username: '李华', age: 26 }

参考

我为什么放弃RESTful,全面拥抱GraphQL

GraphQL一个简单的入门示例

GraphQL示例代码

三、看一个复杂一点的例子

用户User - 博客Blog - 地址Address 三者存在的一对一,一对多关系

服务端代码

var express = require("express");
var { graphqlHTTP } = require("express-graphql");
var {
  GraphQLSchema,
  GraphQLObjectType,
  GraphQLID,
  GraphQLString,
  GraphQLInt,
  GraphQLList,
} = require("graphql");

// 博客
var Blog = new GraphQLObjectType({
  name: "Blog",
  fields: {
    id: { type: GraphQLID },
    title: { type: GraphQLString },
    content: { type: GraphQLString },
    created_time: { type: GraphQLInt },
  },
});

// 地址
var Address = new GraphQLObjectType({
  name: "Address",
  fields: {
    id: { type: GraphQLID },
    name: { type: GraphQLString },
  },
});

// 用户 User 一对一 Address, User 一对多 Blog
var User = new GraphQLObjectType({
  name: "User",
  fields: {
    id: { type: GraphQLID },
    username: { type: GraphQLString },
    password: { type: GraphQLString },
    address: {
      type: Address,
      resolve(parent, args) {
        console.log(parent, args);
        return {
          id: parent.id,
          name: "name" + parent.id,
        };
      },
    },
    blogs: {
      type: new GraphQLList(Blog),
      args: {
        limit: { type: GraphQLInt },
      },
      resolve(parent, args) {
        console.log(parent, args);
        let list = [];
        for (let i =0; i < args.limit; i++) {
          list.push({
            id: i,
            title: "title" + i,
            content: "content" + i,
            created_time: i * 100,
          });
        }
        return list;
      },
    },
  },
});

var Query = new GraphQLObjectType({
  name: "Query",
  fields: {
    user: {
      type: User,
      args: {
        id: { type: GraphQLID },
      },
      resolve(parent, args) {
        console.log(parent, args);
        return {
          id: args.id,
          username: "admin" + args.id,
          password: "123456" + args.id,
        };
      },
    },
  },
});

var schema = new GraphQLSchema({
  query: Query,
});

//  express服务
var app = express();
app.use(
  "/graphql",
  graphqlHTTP({
    schema: schema,
    graphiql: true,
  })
);
app.listen(4000, () => {
  console.log("server at: http://localhost:4000/graphql");
});

客户端请求


const axios = require("axios");

let query = `
  {
    user(id: 3) {
      id
      username
      password
      blogs(limit: 2) {
        id
        title
        content
        created_time
      }
      address {
        id
        name
      }
    }
  }
`
axios.post("http://localhost:4000/graphql", {query}).then((res) => {
  console.log(res.data.data);
});
/**
{ user:
  { 
    id: '3',
    username: 'admin3',
    password: '1234563',
    blogs: [ [Object], [Object] ],
    address: { id: '3', name: 'name3' } 
  } 
}
 */