您当前的位置: 首页 >  node.js

彭世瑜

暂无认证

  • 1浏览

    0关注

    2791博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

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

彭世瑜 发布时间:2021-01-13 13:58:51 ,浏览量:1

在这里插入图片描述 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  {
  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' } 
  } 
}
 */ 

关注
打赏
1665367115
查看更多评论
立即登录/注册

微信扫码登录

0.0572s