Nodejs(④GraphQL)

GraphQL 只需要一次请求就完成了原本需要 6-7 次请求才能获取的完整数据

这就是 GraphQL 最大的优势:减少网络请求次数,精确获取所需数据

安装 GraphQL (Node.js 环境)

复制代码
npm install graphql express-graphql express

示例①GraphQL

javascript 复制代码
const express = require('express');
const { graphqlHTTP } = require('express-graphql');
const { buildSchema } = require('graphql');

// 1. 定义 Schema(数据结构)
const schema = buildSchema(`
  type User {
    id: ID!
    name: String!
    age: Int
  }
  
  type Query {
    hello: String
    user(id: ID!): User
    users: [User]
  }
`);

// 2. 模拟数据
const users = [
  { id: '1', name: '张三', age: 25 },
  { id: '2', name: '李四', age: 30 },
  { id: '3', name: '王五', age: 28 }
];

// 3. 定义 resolver(数据获取逻辑)
const root = {
  hello: () => 'Hello GraphQL!',
  
  user: ({ id }) => {
    return users.find(user => user.id === id);
  },
  
  users: () => users
};

// 4. 创建服务器
const app = express();
app.use('/graphql', graphqlHTTP({
  schema: schema,
  rootValue: root,
  graphiql: true  // 开启图形化界面
}));

app.listen(4000, () => {
  console.log('GraphQL 服务器运行在 http://localhost:4000/graphql');
});

运行服务器

javascript 复制代码
node server.js

然后在浏览器访问:http://localhost:4000/graphql

使用 GraphQL(在 GraphiQL 界面中)

当你的 GraphQL 收到这个查询时:

javascript 复制代码
uery {
  user(id: "2") {
    name
    age
  }
}

背后发生了什么:

GraphQL 看到你要查询 user(id: "2")

它找到对应的 resolver:user: ({ id }) => {...}

它调用这个函数,把 id: "2" 作为参数传进去

函数执行:users.find(user => user.id === "2")

找到 id 为 "2" 的用户:{ id: '2', name: '李四', age: 30 }

返回给客户端

示例②GraphQL

123

相关推荐
IT_陈寒9 分钟前
Java序列化踩坑记:对象循环引用让我加班两小时
前端·人工智能·后端
泡海椒18 分钟前
05-雷达图多维画像-信用评级多维画像
后端
王中阳Go19 分钟前
5.27 分钟干完后端和全部测试:一场三小时笔试的五个失分点,四个不在代码上
大数据·数据库·人工智能·后端·大语言模型
大哥430920 分钟前
Modbus 的"字序":一个配错就变成天文数字,或者干脆变成 0
后端
岩钧24 分钟前
New API 源码解析:一个生产级 AI 网关的架构与实现
后端
学到老活到老30 分钟前
第 24 集:配置文件写了 80,Spring Boot 为什么读到 90?
java·后端·spring
用户3600555790031 分钟前
Kestrel_VLLM - 25 · 全注意力层设备化、整层对拍与访存粒度
后端
yliucherish37 分钟前
从零实现一个 SQL 注入检测引擎:报错注入与布尔盲注的误报控制
后端
bigbread39 分钟前
状态模式-住院患者状态管理
后端
卷无止境2 小时前
给AI装上一双眼睛:快速构建代码验证器的思路与落地方案
后端·python