【问题标题】:context.done called twice within handler 'graphql'context.done 在处理程序“graphql”中调用了两次
【发布时间】:2018-10-23 10:34:24
【问题描述】:

正在尝试基于https://github.com/serverless/serverless-graphql/blob/master/app-backend/dynamodb/handler.js 创建项目。该代码运行良好,但由于某种原因,我总是收到一条日志警告,告诉我context.done called twice

import { graphqlLambda, graphiqlLambda, LambdaHandler } from 'apollo-server-lambda'
import lambdaPlayground from 'graphql-playground-middleware-lambda'
import { makeExecutableSchema } from 'graphql-tools'

import { resolvers } from './resolvers'

const typeDefs = require('./schema.gql')
const schema = makeExecutableSchema({ typeDefs, resolvers, logger: console })

export const graphqlHandler: LambdaHandler = async (event, context) => {
  const handler = graphqlLambda({ schema })
  return handler(event, context, (error: Error | undefined, output: any) => {
    output.headers['Access-Control-Allow-Origin'] = '*'
    context.done(error, output)
  })
}

export const playgroundHandler = lambdaPlayground({
  endpoint: '/graphql',
})

export const graphiqlHandler: any = graphiqlLambda({
  endpointURL: '/graphql',
})

这段代码给了我以下结果:

Serverless: POST /graphql (λ: graphql)
Serverless: [200] {"statusCode":200,"headers":{"Content-Type":"application/json","Access-Control-Allow-Origin":"*"},"body":"{\"data\":{\"getUserInfo\":\"ads\"}}"}

Serverless: Warning: context.done called twice within handler 'graphql'!

更奇怪的是,如果我评论 context.done 调用,我会得到以下输出(调用按预期停止):

Serverless: POST /graphql (λ: graphql)

Serverless: Warning: context.done called twice within handler 'graphql'!

【问题讨论】:

    标签: node.js aws-lambda graphql serverless


    【解决方案1】:

    我遇到了类似的问题。如果您不打算使用 await,请尝试在您的函数中删除异步。当异步不存在时,该函数看起来会一直等到您调用回调或 context.done 。但它一直使用 async 关键字。但是,当它运行时,无论它在函数末尾返回什么,都会调用 context.done。这是一个示例工作代码。

    让我也分享两个来自 aws lambda 的关于 callbackcontext 的有用资源。

    export const handler = (
      {
        headers,
        pathParameters: pathParams,
        queryStringParameters: queryParams,
        body,
      },
      context,
      callback
    ) => {
      context.callbackWaitsForEmptyEventLoop = false;
    
      const data = JSON.parse(body);
      const params = {
        TableName: process.env.EVENT_TABLE,
        Item: {
          id: uuid.v4(),
          title: data.title,
          creationDate: new Date().getTime(),
        },
      };
    
      dynamoDb.put(params, (err, data) => {
        if (err) {
          callback(err);
        }
        callback(null, {
          statusCode: 200,
          body: JSON.stringify(data),
        });
      });
    };
    

    【讨论】:

      【解决方案2】:

      【讨论】:

        猜你喜欢
        • 2012-09-17
        • 1970-01-01
        • 1970-01-01
        • 2011-08-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-12-04
        相关资源
        最近更新 更多