首页 > 解决方案 > TypeGraphQl:使用 Netlify 函数/AWS Lambda

问题描述

经过一天的工作,我终于能够让 TypeQL 与 Netlify Functions / AWS Lambda 一起工作,查看文档和示例,最后绝望的蛮力。

我在这里为其他人分享我的工作代码(或供我自己的 :P 将来参考),因为它包含一些违反直觉的关键字用法。

正常进近

使用简单示例时,我不断遇到的错误是:

Your function response must have a numerical statusCode. You gave: $ undefined

我当然搜索了这些问题,但没有一个建议的解决方案对我有用。

标签: aws-lambdagraphqlnetlifytypegraphqlnetlify-cli

解决方案


工作代码

import 'reflect-metadata'
import { buildSchema } from 'type-graphql'
import { ApolloServer } from 'apollo-server-lambda'
import { RecipeResolver } from 'recipe-resolver'

async function lambdaFunction() {
  const schema = await buildSchema({
    resolvers: [RecipeResolver],
  })

  const server = new ApolloServer({
    schema,
    playground: true,
  })

  // !!! NOTE: return (await ) server.createHandler() won't work !
  exports.handler = server.createHandler()
}

// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// !!! NOTE: weird but only way to make it work with
// AWS lambda and netlify functions (netlify dev)
// also needs a reload of the page (first load of playground won't work)
lambdaFunction()
// exports.handler = lambdaFunction wont work
// export { lambdaFunction as handler } wont work
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

我也从这个简单的例子中得到了一些反射错误

Unable to infer GraphQL type from TypeScript reflection system. You need to provide explicit type for argument named 'title' of 'recipe' of 'RecipeResolver

所以我必须弄清楚如何将显式类型添加到@Arg

// previous:
// recipe(@Arg('title') title: string)
// fixed:
   recipe( @Arg('title', (type) => String) title: string

推荐阅读