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

相关推荐
小村儿1 小时前
连载04-最重要的Skill---一起吃透 Claude Code,告别 AI coding 迷茫
前端·后端·ai编程
IT_陈寒2 小时前
Vite的alias配置把我整不会了,原来是这个坑
前端·人工智能·后端
gelald2 小时前
Spring Boot - 自动配置原理
java·spring boot·后端
希望永不加班2 小时前
SpringBoot 集成测试:@SpringBootTest 与 MockMvc
java·spring boot·后端·log4j·集成测试
uzong2 小时前
软件人员可以关注的 Skill,亲测确实不错,值得试一下
人工智能·后端
掘金虾3 小时前
Hono 框架入门到实战:用 Node.js 写一个支持工具调用的流式对话 Agent
后端
用户8356290780513 小时前
Python 自动拆分 Word 文档教程:按分节符与分页符处理
后端·python
树獭叔叔3 小时前
Claude Code 工具系统深度剖析:从静态注册到动态发现
后端·aigc·openai
树獭叔叔3 小时前
Claude Code 的上下文管理:多层渐进式压缩架构深度解析
后端·aigc·openai
计算机学姐3 小时前
基于SpringBoot的高校竞赛管理系统
java·spring boot·后端·spring·信息可视化·tomcat·mybatis