Failure: Cannot find module handler AWS Lambda

Hello I am trying to setup a new serverless graphql project but the serverless.yml file doesn't find my handler, which is in src/graphql.ts

It throws an error like this:

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

The src is in the root directory and the path is correct, so I don't understand what is going on.

The serverless.yml looks like this:

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

And the graphql handler file like this:

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();

I've also tried

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

But none of that seems to work either.

Has someone any idea of what I am doing wrong? Thank You!

Upvotes: 1

Views: 2135

Answers (1)

Adi
Adi

Reputation: 717

In order to run an AWS Lambda function with a Node.js runtime, you'll need to provide a .js file as its handler. Specifically, when using TypeScript and the Serverless framework, that means that the handler field must refer to the compiled file name, namely, ending with a .js extension.

One option for you to resolve this is to simply change the handler field to point to the compiled version of your file. For example, given the following structure:

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

The correct handler field is:

graphql:
  handler: built/graphql.graphqlHandler

However, another option which I believe is the preferred one (and possibly what you were originally aiming for) is to use the 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 provided by Serverless that is very similar to your need and I think you can find useful.

Upvotes: 2

Related Questions