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

相关推荐
小白男神4 分钟前
MySQL进阶学习三(视图)
后端·mysql
猿人谷5 分钟前
Jev:当 AI 不再生成 Token,而是直接做决策
后端·langchain·aigc
苍何6 分钟前
WorkBuddy + 腾讯乐享,原来知识库还能这么用
后端
站大爷IP9 分钟前
Python的生成器把我坑惨了,原来yield和return的区别这么大
后端
苍何10 分钟前
一份来自大厂内部的《AI 原生实践避坑指南》
后端
codigger33 分钟前
服务器又卡了?一篇讲透 Linux 性能排查(基础四件套 + perf/strace/火焰图)
linux·后端·性能优化
+VX:Fegn089544 分钟前
计算机毕业设计|基于java+ vue共享单车信息系统(源码+数据库+文档)
数据库·vue.js·spring boot·后端·课程设计
苏渡苇1 小时前
Spring Insight 里如何把 Span 画成瀑布时间线
后端·spring·spring cloud·springboot·监控·apm
Charlie_Byte1 小时前
Spring AI 2 手把手:把 filesystem MCP Server 跑通(SSE / stdio + 真调工具)
后端
程序猿DD1 小时前
OctaFuse Gateway 2.11.0:流式请求优化、用户折扣策略与错误契约升级
前端·后端