【问题标题】:Azure functions: Use Apollo Azure handler in async functionAzure 函数:在异步函数中使用 Apollo Azure 处理程序
【发布时间】:2020-10-14 19:24:00
【问题描述】:

我想将我的 apollo 处理程序包装到一个异步函数中,以便在执行处理程序函数之前执行一些检查。一切正常,当我不使用异步函数但将函数导出为异步时,总是返回一个空响应。

functions.json

{
  "bindings": [
    {
      "authLevel": "function",
      "type": "httpTrigger",
      "direction": "in",
      "name": "req",
      "methods": [
        "get",
        "post"
      ]
    },
    {
      "type": "http",
      "direction": "out",
      "name": "$return"
    }
  ],
  "scriptFile": "../dist/graphql/index.js"
}

设置:

    import { buildSchema } from 'type-graphql';
    import { ApolloServer } from 'apollo-server-azure-functions';
    import { Context, HttpRequest } from '@azure/functions';
    
    import { resolvers } from '../src/graphql';
    import { authChecker } from '../src/auth';
    
    const schema = buildSchema({
      resolvers,
      authChecker,
    });
    
    const server = new ApolloServer({
      schema,
      context: ({ context }) => context, // directly use azure Context as Apollo context,
    });
    
    const handler = server.createHandler();

这行得通

export default (context: Context, request: HttpRequest) => {
  handler(context, request);
};

这总是返回 204,空响应

export default async (context: Context, request: HttpRequest) => {
  // do async stuff: await ... 

  handler(context, request);
};

【问题讨论】:

    标签: typescript azure azure-functions apollo apollo-server


    【解决方案1】:

    有两种方法可以从 Node.js Azure 函数返回数据:

    在您的代码中,handler 是来自 apollo-server-azure-functions 包的方法。它在内部调用 context.done() 将响应发送回 Azure 运行时。

    但因为handler(context, request) 本身是一个常规函数调用,所以您导出的顶级async 函数无需等待其完成即可解析。

    您可能希望从异步函数返回一个 Promise,该函数将在底层 apollo 服务器准备好发送响应时解析。这是example implementation

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-01-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-17
      相关资源
      最近更新 更多