You need to implement a simple TODO application using AWS Lambda and Serverless framework.
This application will allow creating/removing/updating/fetching TODO items. Each TODO item can optionally have an attachment image. Each user only has access to TODO items that he/she has created.
The application stores TODO items, and each TODO item contains the following fields:
todoId
(string) - a unique id for an itemuserId
(string) - a unique id for an user creating TODO itemcreatedAt
(string) - date and time when an item was createdname
(string) - name of a TODO item (e.g. "Change a light bulb")dueDate
(string) - date and time by which an item should be completeddone
(boolean) - true if an item was completed, false otherwiseattachmentUrl
(string) (optional) - a URL pointing to an image attached to a TODO item
Following functions are implemented and configured in the serverless.yml
file:
-
Auth
- this function implements a custom authorizer for API Gateway that is be added to all other functions. -
GetTodos
- returns all TODOs for a current user. A user id is extracted from a JWT token that is sent by the frontend
It returns data that looks like this:
{
"items": [
{
"todoId": "123",
"createdAt": "2019-07-27T20:01:45.424Z",
"name": "Buy milk",
"dueDate": "2019-07-29T20:01:45.424Z",
"done": false,
"attachmentUrl": "http://example.com/image.png"
},
{
"todoId": "456",
"createdAt": "2019-07-27T20:01:45.424Z",
"name": "Send a letter",
"dueDate": "2019-07-29T20:01:45.424Z",
"done": true,
"attachmentUrl": "http://example.com/image.png"
},
]
}
CreateTodo
- creates a new TODO for a current user. A shape of data send by a client application to this function can be found in theCreateTodoRequest.ts
file
It receives a new TODO item to be created in JSON format that looks like this:
{
"createdAt": "2019-07-27T20:01:45.424Z",
"name": "Buy milk",
"dueDate": "2019-07-29T20:01:45.424Z",
"done": false,
"attachmentUrl": "http://example.com/image.png"
}
It returns a new TODO item that looks like this:
{
"item": {
"todoId": "123",
"createdAt": "2019-07-27T20:01:45.424Z",
"name": "Buy milk",
"dueDate": "2019-07-29T20:01:45.424Z",
"done": false,
"attachmentUrl": "http://example.com/image.png"
}
}
UpdateTodo
- Updates a TODO item created by a current user. A shape of data send by a client application to this function can be found in theUpdateTodoRequest.ts
file
It receives an object that contains three fields that can be updated in a TODO item:
{
"name": "Buy bread",
"dueDate": "2019-07-29T20:01:45.424Z",
"done": true
}
The id of an item that should be updated is passed as a URL parameter.
It should return an empty body.
DeleteTodo
- should delete a TODO item created by a current user. Expects an id of a TODO item to remove.
It should return an empty body.
GenerateUploadUrl
- returns a pre-signed URL that can be used to upload an attachment file for a TODO item.
It should return a JSON object that looks like this:
{
"uploadUrl": "https://s3-bucket-name.s3.eu-west-2.amazonaws.com/image.png"
}
All functions are connected to appropriate events from API Gateway.
An id of a user can be extracted from a JWT token passed by a client.
Also added any necessary resources to the resources
section of the serverless.yml
file such as DynamoDB table and S3 bucket.
The client
folder contains a web application that can use the API that should be developed in the project.
This frontend should work with your serverless application once it is developed. The file config.ts
in the client
folder configures your client application and contains an API endpoint and Auth0 configuration:
const apiId = '...' API Gateway id
export const apiEndpoint = `https://${apiId}.execute-api.us-east-1.amazonaws.com/dev`
export const authConfig = {
domain: '...', // Domain from Auth0
clientId: '...', // Client id from an Auth0 application
callbackUrl: 'http://localhost:3000/callback'
}
To implement authentication in your application, create an Auth0 application and copy "domain" and "client id" to the config.ts
file in the client
folder. I recommend using asymmetrically encrypted JWT tokens.
The code is configured with Winston logger that creates JSON formatted log statements. You use it to write log messages like this:
import { createLogger } from '../../utils/logger'
const logger = createLogger('auth')
// You can provide additional information with every log statement
// This information can then be used to search for log statements in a log storage system
logger.info('User was authorized', {
// Additional information stored with a log statement
key: 'value'
})
To store TODO items, you might want to use a DynamoDB table with local secondary index(es). A create a local secondary index you need to create a DynamoDB resource like this:
TodosTable:
Type: AWS::DynamoDB::Table
Properties:
AttributeDefinitions:
- AttributeName: partitionKey
AttributeType: S
- AttributeName: sortKey
AttributeType: S
- AttributeName: indexKey
AttributeType: S
KeySchema:
- AttributeName: partitionKey
KeyType: HASH
- AttributeName: sortKey
KeyType: RANGE
BillingMode: PAY_PER_REQUEST
TableName: ${self:provider.environment.TODOS_TABLE}
LocalSecondaryIndexes:
- IndexName: ${self:provider.environment.INDEX_NAME}
KeySchema:
- AttributeName: partitionKey
KeyType: HASH
- AttributeName: indexKey
KeyType: RANGE
Projection:
ProjectionType: ALL # What attributes will be copied to an index
To query an index you need to use the query()
method like:
//file:todoAccess.ts
await this.dynamoDBClient
.query({
TableName: 'table-name',
IndexName: 'index-name',
KeyConditionExpression: 'paritionKey = :paritionKey',
ExpressionAttributeValues: {
':paritionKey': partitionKeyValue
}
})
.promise()
To deploy an application run the following commands: configure your sls
sls config --provider aws --key <Iam Key> --secret <Iam Secret> --profile 'serverless'
cd backend
npm install
export NODE_OPTIONS=--max_old_space_size=8192
sls deploy -v --aws-profile serverless
Note
: I have made my default region as ap-south-1
in serverless.yml
To run a client application first edit the client/src/config.ts
file to set correct parameters.
Parameters like
- apiId
- apiEndpoint
- authConfig
- domain
- clientId
- callbackUrl And then run the following commands:
cd client
npm install
npm run start
This should start a development server with the React application that will interact with the serverless TODO application.
- LocalSecondaryIndexes (LSI) has been made for linking two datatypes
- RS256algorith is used for Authorization
- Logging of API is enabled
- Documentation is also enabled
- Tracing of lambda function and API Gateway through Amazon XRay
- CORS policy enabled
- Using Json schema for validation
- Authentication using third party service i.e. Auth0 here