...

/

Writing Our First Create Lambda Code

Writing Our First Create Lambda Code

Learn to write lambda code to create reservations through the POST method.

We'll cover the following...

Overview

This time we’ll use TDD to develop our application. For our first code, we’ll be very explicit about the thought process. Later on, this will become implicit because this course would become way too long if we built all our code incrementally, through frequent testing.

The first thing we want to do when we receive an event in our Lambda is to change it into a format we can actually work with and conduct some checks to see whether the information we received is valid (never trust frontend data). For example, we should confirm that the end date is later than the start date.

Setup

Create a folder under create called __tests__. Because we only have one function right now, we’ll put almost everything we write in the directory of the Create Lambda. If we notice we need certain functions elsewhere, in another Lambda, we’ll move them to a common module. Create a folder called specifics under our test folder. We’ll call our first test file anticorruptionTest.ts. In DDD, an anti-corruption layer is often our first line of defense against the outside world. It can check incoming information and transform it into something that’s actually useful to our domain. This layer’s modest, in our case. Add the following to the file:

Press + to interact
import * as E from "fp-ts/Either";
const getResult = (either: any) => {
return E.getOrElseW((err) => err)(either);
}
describe('anti corruption checks', () => {
it('should fail when there is no start or end date', () => {
const now = new Date();
const eventData = {
hotelId: '1',
userId: '10',
start: '',
end: '',
timestamp: now,
}
const event = {
body: JSON.stringify(eventData)
}
const result = getResult(
fromEventToCreateRequest(event)
);
expect(result).toBe('Start date should be before end date');
});
});

In recent years, developers have been advised to organize their code by component, not by layer. Instead of a module containing everything related to the controller (UserController, MoneyController), service (UserService, MoneyService), or database, a module holds everything related to a certain concept in our domain (UserController, UserService, ...