gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 20:27:06 24 4
gpt4 key购买 nike

使用apollo-server-lambda在无服务器的lambda服务器中设置cookie

我正在从apollo服务器迁移到无服务器版本。有没有一种方法可以访问响应对象或另一种设置Cookie的方法?

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

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

最佳答案

我找不到使用apollo-server-lambda做到这一点的方法,所以我所做的就是结合使用apollo-server-expressserverless-http。下面的代码正在使用导入/导出,因为我正在使用 typescript 。

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,
});
}


另一个有用的 resource

关于lambda - 如何在apollo-server-lambda中处理cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57608975/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com