
本文档旨在指导开发者在使用 Apollo Server 搭建 GraphQL 服务时,如何通过 WebSocket 连接获取请求的 Context 信息,包括身份验证 Token 等。我们将详细介绍配置步骤,并提供示例代码,帮助你理解如何在 WebSocket 环境下正确地传递和使用 Context。
在使用 Apollo Server 构建 GraphQL 服务时,如果需要通过 WebSocket 来处理订阅(Subscription)等实时数据,获取请求上下文(Context)的方式与传统的 HTTP 请求有所不同。以下将介绍如何在 WebSocket 环境下正确配置和获取 Context。
首先,需要确保正确配置了 WebSocket 服务器和 Apollo Server。以下是一个示例配置:
import { ApolloServer } from '@apollo/server';
import { createServer } from 'http';
import { expressMiddleware } from '@apollo/server/express4';
import express from 'express';
import { ApolloServerPluginDrainHttpServer } from '@apollo/server/plugin/drainHttpServer';
import { makeExecutableSchema } from '@graphql-tools/schema';
import { WebSocketServer } from 'ws';
import { useServer } from 'graphql-ws/lib/use/ws';
import { resolvers, typeDefs } from './src/graphql/modules/index.js';
import jwt from 'jsonwebtoken';
import cors from 'cors';
import bodyParser from 'body-parser';
import { PubSub } from 'graphql-subscriptions';
const app = express();
const httpServer = createServer(app);
const schema = makeExecutableSchema({ typeDefs, resolvers });
const wsServer = new WebSocketServer({
server: httpServer,
path: '/graphql',
});
const pub = new PubSub();
const serverCleanup = useServer(
{ schema,
context: async (ctx, msg, args) => {
// 从 WebSocket 连接的 headers 中获取 token
const token = ctx.extra.request.headers.authorization?.split(' ')[1];
let currentUser = null;
if (token) {
try {
currentUser = jwt.decode(token, process.env.SECRET);
} catch (e) {
console.error('Token decoding error:', e);
}
}
return { currentUser, pub };
}
},
wsServer
);
const server = new ApolloServer({
schema,
plugins: [
ApolloServerPluginDrainHttpServer({ httpServer }),
{
async serverWillStart() {
return {
async drainServer() {
await serverCleanup.dispose();
},
};
},
},
],
});
await server.start();
// 使用 expressMiddleware 处理 HTTP 请求,并注入 context
app.use(
'/graphql',
cors(),
bodyParser.json(),
expressMiddleware(server, {
context: async ({ req }) => {
const token = req.headers.authorization?.split(' ')[1];
let currentUser = null;
if (token) {
try {
currentUser = jwt.decode(token, process.env.SECRET);
} catch (e) {
console.error('Token decoding error:', e);
}
}
return { currentUser };
},
})
);
httpServer.listen(4000, () => {
console.log('Server is running on port 4000');
});代码解释:
在解析器中,可以通过 contextValue 参数访问 Context 中的数据。
const resolvers = {
Query: {
notificacoesUsuario(_, args, contextValue) {
// 从 contextValue 中获取 currentUser
const { currentUser } = contextValue;
if (!currentUser) {
throw new GraphQLError('User is not authenticated', {
extensions: {
code: 'UNAUTHENTICATED',
http: { status: 401 },
},
});
}
return notificacaoDb.getByReceptor(currentUser.id);
},
visualizarNotificacao(_, { id }) {
return notificacaoDb.visualizarNotificacao(id);
},
},
Notificacao: {
data(args) {
return args.data.toISOString();
},
},
Subscription: {
notificacaoCriada: {
subscribe: (_, {}, context) => context.pub.asyncIterator(['NOTIFICACAO_CRIADA']),
},
},
};
export default { resolvers };代码解释:
客户端需要确保在建立 WebSocket 连接时,将 Token 通过 Authorization 头传递给服务器。例如:
import { createClient } from 'graphql-ws';
const client = createClient({
url: 'ws://localhost:4000/graphql',
connectionParams: {
headers: {
Authorization: `Bearer ${localStorage.getItem('token')}`,
},
},
});代码解释:
本文档介绍了在使用 Apollo Server 搭建 GraphQL 服务时,如何通过 WebSocket 连接获取请求的 Context 信息。通过正确配置 WebSocket 服务器和 Apollo Server,并合理使用 useServer 函数,可以轻松地在 WebSocket 环境下获取和使用 Context 信息,实现身份验证和权限控制等功能。
以上就是在 Apollo Server 中使用 WebSocket 获取 Context的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号