如何处理 apollo-server-lambda 中的 cookie



在 lambda 中设置 cookie 无服务器与 apollo-server-lambda

我正在从阿波罗服务器迁移到无服务器版本。有没有办法访问响应对象或其他方法来设置 cookie?

context: ({ event, context }) => ({
headers: event.headers,
functionName: context.functionName,
event,
context,
}),

我希望在上下文中可以访问 res 对象,就像它在阿波罗服务器中一样。

我找不到使用 apollo-server-lambda 的方法,所以我所做的是结合使用 apollo-server-express 和 serverless-http。下面的代码正在使用导入/导出,因为我使用的是打字稿。

Serverless-http 接受各种类似 Express 的框架。

import express from 'express'; // <-- IMPORTANT
import serverlessHttp from 'serverless-http'; // <-- IMPORTANT
import { ApolloServer } from 'apollo-server-express'; // <-- IMPORTANT
import typeDef from './typeDef';
import resolvers from './resolvers';
export const server = new ApolloServer({
typeDef,
resolvers,
context: async ({ req, res }) => {
/**
* you can do anything here like check if req has a session,
* check if the session is valid, etc...
*/
return {
// things that it'll be available to the resolvers
req,
res,
};
},
});
const app = express(); // <-- IMPORTANT
server.applyMiddleware({ app }); // <-- IMPORTANT
// IMPORTANT
// by the way, you can name the handler whatever you want
export const graphqlHandler = serverlessHttp(app, {
/** 
* **** IMPORTANT ****
* this request() function is important because 
* it adds the lambda's event and context object 
* into the express's req object so you can access
* inside the resolvers or routes if your not using apollo
*/
request(req, event, context) { 
req.event = event;
req.context = context;
},
});

例如,现在您可以在解析器中使用res.cookie()

import uuidv4 from 'uuid/v4';
export default async (parent, args, context) => {
// ... function code
const sessionID = uuidv4();
// a example of setting the cookie
context.res.cookie('session', sessionID, {
httpOnly: true,
secure: true,
path: '/',
maxAge: 1000 * 60 * 60 * 24 * 7,
});
}

另一个有用的资源

您需要一种方法来设置解析程序中的响应标头。

您可以做的是为解析程序中的上下文对象设置一个值。

const resolver = (parent, args, { context }) => {
context.addHeaders = [{ key: 'customheader', value: 'headervalue'}]
}

您可以通过创建 Apollo 服务器插件来捕获服务器生命周期中willSendResponse事件中的上下文。然后,可以将标头从customHeaders属性添加到GraphQLResponse对象。

const customHeadersPlugin = {
requestDidStart(requestContext) {
return {
willSendResponse(requestContext) {
const {
context: { addHeaders = [] }
} = requestContext.context
addHeaders.forEach(({ key, value }) => {
requestContext.response.http.headers.append(key, value)
})
return requestContext
}
}
}
}

您需要在阿波罗服务器中加载插件。

const server = new ApolloServer({
typeDefs,
resolvers,
plugins: [customHeadersPlugin],
context: ({ context }) => ({
context
})
})

现在,您有一种方法可以修改解析程序中的响应标头。为了能够设置 Cookie,您可以使用 cookie 字符串或使用 cookie 库手动设置Set-Cookie标头。


感谢 Apollo GraphQL 团队的 Trevor Scheer 在我需要自己实现时为我指明了正确的方向。

您可以使用 apollo-server-plugin-http-headers 包。

在解析器中,用法非常简单:

context.setCookies.push({
name: "cookieName",
value: "cookieContent",
options: {
domain: "example.com",
expires: new Date("2021-01-01T00:00:00"),
httpOnly: true,
maxAge: 3600,
path: "/",
sameSite: true,
secure: true
}
});

最新更新