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

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

image.png

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' } 
  } 
}
 */ 
相关文章
|
2月前
|
Web App开发 缓存 JavaScript
【安装指南】nodejs下载、安装与配置详细教程
这篇博文详细介绍了 Node.js 的下载、安装与配置过程,为初学者提供了清晰的指南。读者通过该教程可以轻松完成 Node.js 的安装,了解相关配置和基本操作。文章首先介绍了 Node.js 的背景和应用场景,随后详细说明了下载安装包、安装步骤以及配置环境变量的方法。作者用简洁明了的语言,配以步骤图示,使得读者能够轻松跟随教程完成操作。总的来说,这篇文章为初学者提供了一个友好的入门指南,使他们能够顺利开始使用 Node.js 进行开发。
149 1
【安装指南】nodejs下载、安装与配置详细教程
|
4月前
|
JavaScript Linux
(简单成功详细)CentOS 安装 node.js
(简单成功详细)CentOS 安装 node.js
362 1
|
2月前
|
消息中间件 Web App开发 JavaScript
Node.js【简介、安装、运行 Node.js 脚本、事件循环、ES6 作业队列、Buffer(缓冲区)、Stream(流)】(一)-全面详解(学习总结---从入门到深化)
Node.js【简介、安装、运行 Node.js 脚本、事件循环、ES6 作业队列、Buffer(缓冲区)、Stream(流)】(一)-全面详解(学习总结---从入门到深化)
70 0
|
3月前
|
JavaScript 前端开发 API
Node.js【简介、安装、运行 Node.js 脚本、事件循环、ES6 作业队列、Buffer(缓冲区)、Stream(流)】(一)-全面详解(学习总结---从入门到深化)(下)
Node.js【简介、安装、运行 Node.js 脚本、事件循环、ES6 作业队列、Buffer(缓冲区)、Stream(流)】(一)-全面详解(学习总结---从入门到深化)
34 0
|
3月前
|
消息中间件 Web App开发 JavaScript
Node.js【简介、安装、运行 Node.js 脚本、事件循环、ES6 作业队列、Buffer(缓冲区)、Stream(流)】(一)-全面详解(学习总结---从入门到深化)(上)
Node.js【简介、安装、运行 Node.js 脚本、事件循环、ES6 作业队列、Buffer(缓冲区)、Stream(流)】(一)-全面详解(学习总结---从入门到深化)
42 0
|
12天前
|
JavaScript Windows
NodeJS 安装及环境配置
NodeJS 安装及环境配置
|
21天前
|
Linux 开发工具 git
node使用nrm 管理托管node的安装源
node使用nrm 管理托管node的安装源
35 1
|
1月前
|
Web App开发 JavaScript 前端开发
Windows 10上安装Node.js的初学者指南
Node.js是是一个强大的JavaScript运行时环境,建立在Chrome的V8 JavaScript引擎上,让你能够在服务器端运行JavaScript。 通过本教程,你将学会如何设置Node.js和npm(节点包管理器等现代Web开发的必备工具。无论你是希望构建Web应用程序、创建服务器端脚本,还是涉足全栈开发,安装Node.js都是你的第一步。那么,让我们开始吧!
|
2月前
|
JavaScript
记录安装nodejs遇到的问题及解决
最近在搭建网站,需要用到nodejs,在配置的时候遇到3个问题,经过搜索和自己思考,把遇到的问题和解决方案记录下来,以供参考
|
2月前
|
JavaScript Windows 内存技术
通过Nvm安装和管理NodeJS
通过Nvm安装和管理NodeJS
104 0
通过Nvm安装和管理NodeJS