前端Apollo Client对接AWS Lambda:如何使用纯GraphQL.js实现?
如何用纯GraphQL.js实现AWS Lambda的GraphQL服务(配合前端Apollo Client调用)
我懂你的顾虑——在Lambda上套Apollo Server确实有点“杀鸡用牛刀”的感觉,用纯graphql包来实现其实更轻量直接,完全能满足接收前端Apollo Client请求的需求。下面是具体的实现步骤:
1. 安装核心依赖
在你的Lambda项目目录下,只需要安装官方的graphql包就够了:
npm install graphql
2. 定义GraphQL Schema和Resolver
先写好你的Schema定义和对应的Resolver逻辑,这部分和你用Apollo时的写法基本一致,只是不需要Apollo的封装:
// schema.js const { buildSchema } = require('graphql'); // 定义Schema const schema = buildSchema(` type User { id: ID! name: String! email: String! } type Query { getUser(id: ID!): User getAllUsers: [User] } type Mutation { createUser(name: String!, email: String!): User } `); // 模拟数据源(实际项目可以换成DynamoDB、RDS等) const users = [ { id: '1', name: 'Alice', email: 'alice@example.com' }, { id: '2', name: 'Bob', email: 'bob@example.com' } ]; // 定义Resolver const root = { getUser: ({ id }) => users.find(user => user.id === id), getAllUsers: () => users, createUser: ({ name, email }) => { const newUser = { id: String(users.length + 1), name, email }; users.push(newUser); return newUser; } }; module.exports = { schema, root };
3. 编写Lambda处理函数
这是核心部分,需要处理API Gateway传来的请求,解析GraphQL的查询内容,然后调用graphql的execute方法执行查询,最后返回符合规范的响应:
// handler.js const { execute } = require('graphql'); const { schema, root } = require('./schema'); exports.handler = async (event) => { try { // 解析请求体(API Gateway的POST请求会把数据存在event.body里) const { query, variables } = JSON.parse(event.body); // 执行GraphQL查询 const result = await execute({ schema, document: query, rootValue: root, variableValues: variables }); // 返回响应,注意设置CORS头(如果前端是浏览器端调用) return { statusCode: 200, headers: { 'Access-Control-Allow-Origin': '*', // 生产环境建议指定具体域名 'Access-Control-Allow-Headers': 'Content-Type' }, body: JSON.stringify(result) }; } catch (error) { // 处理错误,返回符合GraphQL规范的错误格式 return { statusCode: 400, headers: { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Headers': 'Content-Type' }, body: JSON.stringify({ errors: [{ message: error.message }] }) }; } };
4. 前端Apollo Client配置
前端这边完全不需要改动,只需要把Apollo Client的uri指向你的Lambda对应的API Gateway端点就行:
// 前端Apollo Client配置 import { ApolloClient, InMemoryCache, createHttpLink } from '@apollo/client'; const httpLink = createHttpLink({ uri: 'https://your-api-gateway-endpoint.amazonaws.com/prod/graphql', // 替换成你的实际端点 }); const client = new ApolloClient({ link: httpLink, cache: new InMemoryCache(), });
注意事项
- CORS配置:如果前端是浏览器端跨域调用,一定要在Lambda的响应头里设置
Access-Control-Allow-Origin,生产环境别用*,指定具体的前端域名。 - API Gateway配置:要把API Gateway设置为代理集成,确保请求的body、headers能完整传递给Lambda,并且把响应直接返回给前端。
- 错误处理:Lambda里要捕获解析错误、执行错误,返回符合GraphQL规范的错误格式,这样前端Apollo Client才能正确处理错误。
这样一套下来,你就用纯graphql.js在Lambda上实现了GraphQL服务,完全能对接前端的Apollo Client,而且比用Apollo Server要轻量很多~
内容的提问来源于stack exchange,提问作者tmp dev
相关产品推荐
相关产品推荐

