失败:找不到模块处理程序 AWS Lambda

Failure: Cannot find module handler AWS Lambda

您好,我正在尝试设置一个新的无服务器 graphql 项目,但是 serverless.yml 文件找不到我的处理程序,它位于 src/graphql.ts

它抛出这样的错误:

Failure: Cannot find module '/Users/VIU/Projects/am/src/graphql'

src在根目录下,路径是正确的,所以我不明白是怎么回事。

serverless.yml 看起来像这样:

graphql:
  handler: src/graphql.graphqlHandler
  events:
    - http:
        path: graphql
        method: post
        cors: true
    - http:
        path: graphql
        method: get
        cors: true

像这样的 graphql 处理程序文件:

import { ApolloServer, gql } from "apollo-server-lambda"

// Construct a schema, using GraphQL schema language
const typeDefs = gql`
  type Query {
    hello: String
  }
`;

// Provide resolver functions for your schema fields
const resolvers = {
  Query: {
    hello: () => 'Hello world!',
  },
};

const server = new ApolloServer({ typeDefs, resolvers });

exports.graphqlHandler = server.createHandler();

我也试过了

module.exports.graphqlHandler = server.createHandler();
export const graphqlHandler = server.createHandler();

但是 none 似乎也有效。

有人知道我做错了什么吗?谢谢!

为了 运行 具有 Node.js 运行 时间的 AWS Lambda 函数,您需要提供一个 .js 文件作为其处理程序。具体来说,当使用 TypeScript 和 Serverless 框架时,这意味着 handler 字段必须引用编译后的文件名,即以 .js 扩展名结尾。

解决此问题的一个方法是简单地更改 handler 字段以指向文件的编译版本。例如,给定以下结构:

├── am
│   ├── built
│   │   └── graphql.js
│   ├── package-lock.json
│   ├── package.json
│   └── src
│       └── graphql.ts
└── serverless.yaml

正确的 handler 字段是:

graphql:
  handler: built/graphql.graphqlHandler

但是,我认为另一种选择(可能是您最初的目标)是使用 Serverless 提供的与您的需求非常相似的 serverless-plugin-typescript plugin of the Serverless framework. That should reduce your efforts and allow you to use TypeScript almost seamlessly. There is actually an example,我认为您可以觉得有用。