Skip to content

Instantly share code, notes, and snippets.

@niklaskeerl
Created September 7, 2024 09:47
Show Gist options
  • Save niklaskeerl/9b22b29474dd8ad7f0f41c7a08762fc1 to your computer and use it in GitHub Desktop.
Save niklaskeerl/9b22b29474dd8ad7f0f41c7a08762fc1 to your computer and use it in GitHub Desktop.
Transform AWS Typescript Lambda to Typescript Express.js Application for ECS / EKS / Elastic Beanstalk

Transform Typescript AWS Lambda to Express.js Applications

Motivation

AWS Lambda is not always the ideal choice for your application. This can have numerous reasons e.g. your customers are annoyed from the cold startup times, you need a higher request body size or your application has very long running tasks which are interrupted.

To go around all of this issues we should have a long running application. Express.js is a popular choice for building Typescript and Javascript REST APIs. We can levarage it to transform our AWS lambda app to a long running Rest API.

Implementation

Your code probably looks a little bit similar to this:

export const handler: APIGatewayProxyHandler = LambdaRouter.build((routes) =>
  routes
    .head("/accounts/${username}")(async (r) => {
      const accountExists = await Domain.accountExists(r.pathParams.username);
      return r.response(accountExists ? 200 : 404, "");
    })
    .get("/accounts/${username}")((r) =>
      Domain.getAccount(r.pathParams.username).then((a) =>
        r.response(a ? 200 : 404, a)
      )
    )
    .post("/echo")(
    (r) =>
      Domain.saveAccount(r.body)
        .then((id) =>
          r.response(201, {
            accountId: id,
          })
        )
        .catch((e) => {
          console.log("Error saving account", e);
          return r.response(400, {
            message: "Error",
          });
        })
  )

We want to move a code that looks similar to this:

mport express from 'express';

const app = express();
app.use(express.json());

app.get('/hello', (req, res) => {
    res.status(200).json({ message: 'Hello, world!' });
});

app.post('/echo', (req, res) => {
    const body = req.body;
    res.status(200).json({ message: 'Echo', data: body });
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
    console.log(`Server is running on port ${PORT}`);
});

As you can see, we have to change the wrapper code for each function a little bit and how we access the request and response. Otherwise the implementation of each function can stay the same.

Once you are done, you can either upload it directly to AWS Elastic Beanstalk or build an container and run it in Elastic Container Service or Elastic Kubernetes Service.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment