登录
首页 >  文章 >  前端

Node.js实现GraphQL实时订阅教程

时间:2026-01-17 23:59:46 132浏览 收藏

今日不肯埋头,明日何以抬头!每日一句努力自己的话哈哈~哈喽,今天我将给大家带来一篇《Node.js实现GraphQL实时订阅API指南》,主要内容是讲解等等,感兴趣的朋友可以收藏或者有更好的建议在评论提出,我都会认真看的!大家一起进步,一起学习!

使用graphql-ws实现GraphQL订阅需结合WebSocket与发布-订阅模式。1. 安装express、graphql、ws、graphql-ws等依赖;2. 定义含Subscription类型的Schema并编写返回AsyncIterator的解析器;3. 用ws创建WebSocket服务器,通过useServer集成graphql-ws;4. 启动HTTP服务并可选添加express-graphql支持调试界面;5. 前端通过WebSocket连接发送订阅请求,服务端在Mutation中发布事件触发实时推送。关键在于路径一致与正确使用PubSub和AsyncIterator。

如何用Node.js实现一个支持GraphQL订阅的实时API?

要实现一个支持GraphQL订阅的实时API,核心是使用WebSocket来建立持久连接,并结合GraphQL执行机制推送数据更新。Node.js生态中,graphql-wssubscriptions-transport-ws是主流选择。推荐使用更现代、轻量且兼容性更好的graphql-ws库,配合expressgraphql构建完整服务。

1. 安装必要依赖

先初始化项目并安装关键包:

npm init -y
npm install express graphql express-graphql ws graphql-ws

2. 定义GraphQL Schema和解析器

创建基本的Schema,包含查询和订阅类型:

const { buildSchema } = require('graphql');

const schema = buildSchema(` type Post { id: ID! title: String! content: String }

type Query { posts: [Post] }

type Subscription { postAdded: Post } `);

编写解析器,其中订阅返回一个AsyncIterator

const posts = []; const { PubSub } = require('graphql'); const pubsub = new PubSub();

const resolvers = { Query: { posts: () => posts },
Subscription: { postAdded: { subscribe: () => pubsub.asyncIterator(['POST_ADDED']) } },
Mutation: { addPost: ({ title, content }) => { const post = { id: posts.length + 1, title, content }; posts.push(post); pubsub.publish('POST_ADDED', { postAdded: post }); return post; } } };

3. 配置WebSocket服务器支持订阅

使用ws创建WebSocket服务器,并通过graphql-ws处理订阅消息:

const express = require('express'); const { createServer } = require('http'); const { useServer } = require('graphql-ws/lib/use/ws'); const { WebSocketServer } = require('ws');

const app = express(); const server = createServer(app);

// 创建WebSocket服务器用于GraphQL订阅 const wss = new WebSocketServer({ server, path: '/graphql' });

useServer({ schema, execute, subscribe }, wss);

注意:executesubscribe来自graphql模块,需导入:

const { execute, subscribe } = require('graphql');

4. 启动HTTP和WebSocket服务

让Express处理普通请求,WebSocket处理实时通信:

server.listen(4000, () => { console.log('HTTP服务器运行在 http://localhost:4000'); console.log('WebSocket服务器已启动,路径 /graphql'); });

可选:添加express-graphql中间件支持浏览器调试:

const { graphqlHTTP } = require('express-graphql');

app.use('/graphql', graphqlHTTP({ schema, rootValue: resolvers, graphiql: true // 启用GraphiQL界面 }));

5. 前端测试订阅功能

在客户端使用graphql-wsurql等库连接。示例使用原生WebSocket:

const ws = new WebSocket('ws://localhost:4000/graphql');

ws.onopen = () => { ws.send(JSON.stringify({ type: 'subscribe', payload: { query: `subscription { postAdded { id title content } }` } })); };

ws.onmessage = (event) => { console.log('收到新帖子:', JSON.parse(event.data)); };

当调用addPost mutation时,所有订阅客户端会立即收到更新。

基本上就这些。关键是把WebSocket和GraphQL执行流程打通,用发布-订阅模式触发实时推送。整个过程不复杂但容易忽略细节,比如路径一致性和AsyncIterator的正确使用。

以上就是《Node.js实现GraphQL实时订阅教程》的详细内容,更多关于的资料请关注golang学习网公众号!

前往漫画官网入口并下载 ➜
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>