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

相关推荐
学长毕设7 小时前
基于SpringBoot的儿童慈善捐赠管理系统-附源码
java·spring boot·后端
皮皮林5518 小时前
GitHub Copilot:你可以暂时不用,但别不知道它有多强
后端
学长毕设8 小时前
基于SpringBoot非遗文化展示与传播平台设计与实现-附源码
java·spring boot·后端
杨凯凡9 小时前
Spring Boot SSE 上线后不实时、频繁断线?Nginx 缓冲、心跳与连接回收实战
spring boot·后端·nginx
锋行天下10 小时前
langgraph 全栈项目(三)
前端·人工智能·后端
金銀銅鐵10 小时前
用 Swing 重做操作数栈演示
java·jvm·后端
锋行天下10 小时前
langgraph 全栈项目(二)
前端·人工智能·后端
锋行天下11 小时前
langgraph全栈项目(一)
前端·人工智能·后端
学长毕设11 小时前
基于SpringBoot的游戏攻略社区交流系统-附源码
spring boot·后端·游戏
程序员cxuan11 小时前
不得了,Google 造反了,Opus 5.5 又被干了
人工智能·后端·程序员