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.
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.