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

相关推荐
开心猴爷几秒前
苹果商店 App 上架要求,探讨如何通过系统审核
后端
开心就好20251 分钟前
Flutter 应用加固在真实项目中的实践方式,当 Dart 之外还有一整个 IPA
后端
黄俊懿6 分钟前
【深入理解SpringCloud微服务】Spring-Security作用与原理解析
java·后端·安全·spring·spring cloud·微服务·架构师
我是谁的程序员7 分钟前
iOS 开发中证书创建与管理中的常见问题
后端
塔能物联运维14 分钟前
设备自适应采样率忽视能耗致续航降 后来结合功耗模型动态调优
java·后端·struts
我是谁的程序员15 分钟前
iPhone 耗电异常检测的思路,从系统电池统计、克魔(KeyMob)、Instruments等工具出发
后端
掘金一周20 分钟前
前端一行代码生成数千页PDF,dompdf.js新增分页功能| 掘金一周 12.25
前端·javascript·后端
ServBay21 分钟前
掌握这9个GO技巧,代码高效又高能
后端·go
rchmin23 分钟前
Spring Boot自动装配原理解析
java·spring boot·后端
程序员小假29 分钟前
我们来说一下 synchronized 与 ReentrantLock 的区别
java·后端