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

Pop*_*lex 10 lambda graphql apollo-server serverless

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

我正在从 apollo-server 迁移到无服务器版本。有没有办法可以访问响应对象或其他方式来设置 cookie?

context: ({ event, context }) => ({
   headers: event.headers,
   functionName: context.functionName,
   event,
   context,
 }),
Run Code Online (Sandbox Code Playgroud)

我期望在上下文中可以像在 apollo-server 中一样访问 res 对象。

Luc*_*nti 5

我找不到使用 apollo-server-lambda 做到这一点的方法,所以我所做的是结合使用apollo-server-expressserverless-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;
    },
});
Run Code Online (Sandbox Code Playgroud)

例如,现在您可以在解析器中使用 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,
    });
}

Run Code Online (Sandbox Code Playgroud)

另一个有用的资源