├── src ├── enums │ ├── status.enum.ts │ ├── status-code.enum.ts │ └── response-message.enum.ts ├── constraints │ ├── list │ │ ├── get.constraint.json │ │ ├── create.constraint.json │ │ └── update.constraint.json │ └── task │ │ ├── get.constraint.json │ │ ├── delete.constraint.json │ │ ├── create.constraint.json │ │ └── update.constraint.json ├── models │ ├── list.model.ts │ ├── response.model.ts │ └── task.model.ts ├── utils │ ├── lambda-handler.ts │ └── util.ts ├── actions │ ├── task │ │ ├── get-task.action.ts │ │ ├── delete-task.action.ts │ │ ├── create-task.action.ts │ │ └── update-task.action.ts │ └── list │ │ ├── create-list.action.ts │ │ ├── update-list.action.ts │ │ ├── get-list.action.ts │ │ └── delete-list.action.ts └── services │ └── database.service.ts ├── check ├── http-client.env.json └── rest-api.http ├── .gitignore ├── .eslintrc.js ├── tsconfig.json ├── handler.ts ├── README.md ├── ops-handler.ts ├── LICENSE ├── package.json ├── resources ├── cloudwatch-alarms.ts ├── dynamodb-tables.ts └── functions.ts └── serverless.ts /src/enums/status.enum.ts: -------------------------------------------------------------------------------- 1 | export enum Status { 2 | SUCCESS = "success", 3 | ERROR = "error", 4 | BAD_REQUEST = "bad request", 5 | } 6 | -------------------------------------------------------------------------------- /src/constraints/list/get.constraint.json: -------------------------------------------------------------------------------- 1 | { 2 | "listId": { 3 | "presence": { 4 | "allowEmpty": false 5 | }, 6 | "type": "string" 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/constraints/list/create.constraint.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": { 3 | "presence": { 4 | "allowEmpty": false, 5 | "type": "string" 6 | } 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/enums/status-code.enum.ts: -------------------------------------------------------------------------------- 1 | export enum StatusCode { 2 | OK = 200, 3 | CREATED = 201, 4 | NO_CONTENT = 204, 5 | BAD_REQUEST = 400, 6 | NOT_FOUND = 404, 7 | ERROR = 500, 8 | } 9 | -------------------------------------------------------------------------------- /check/http-client.env.json: -------------------------------------------------------------------------------- 1 | { 2 | "dev": { 3 | "baseUrl": "localhost:3000/dev" 4 | }, 5 | "prod": { 6 | "baseUrl": "https://ng8kpyntcd.execute-api.ap-northeast-1.amazonaws.com/prod" 7 | } 8 | } -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # package directories 2 | node_modules 3 | jspm_packages 4 | 5 | # Serverless directories 6 | .serverless 7 | 8 | # Webpack directories 9 | .webpack 10 | 11 | .env.*.local 12 | 13 | .vscode 14 | .idea 15 | .dynamodb 16 | *.iml -------------------------------------------------------------------------------- /src/constraints/list/update.constraint.json: -------------------------------------------------------------------------------- 1 | { 2 | "listId": { 3 | "presence": { 4 | "allowEmpty": false 5 | }, 6 | "type": "string" 7 | }, 8 | "name": { 9 | "presence": { 10 | "allowEmpty": false 11 | }, 12 | "type": "string" 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/constraints/task/get.constraint.json: -------------------------------------------------------------------------------- 1 | { 2 | "listId": { 3 | "presence": { 4 | "allowEmpty": false 5 | }, 6 | "type": "string" 7 | }, 8 | "taskId": { 9 | "presence": { 10 | "allowEmpty": false 11 | }, 12 | "type": "string" 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/constraints/task/delete.constraint.json: -------------------------------------------------------------------------------- 1 | { 2 | "listId": { 3 | "presence": { 4 | "allowEmpty": false 5 | }, 6 | "type": "string" 7 | }, 8 | "taskId": { 9 | "presence": { 10 | "allowEmpty": false 11 | }, 12 | "type": "string" 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/constraints/task/create.constraint.json: -------------------------------------------------------------------------------- 1 | { 2 | "listId": { 3 | "presence": { 4 | "allowEmpty": false 5 | }, 6 | "type": "string" 7 | }, 8 | "description": { 9 | "presence": { 10 | "allowEmpty": false 11 | }, 12 | "type": "string" 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/constraints/task/update.constraint.json: -------------------------------------------------------------------------------- 1 | { 2 | "listId": { 3 | "presence": { 4 | "allowEmpty": false 5 | }, 6 | "type": "string" 7 | }, 8 | "taskId": { 9 | "presence": { 10 | "allowEmpty": false 11 | }, 12 | "type": "string" 13 | }, 14 | "description": { 15 | "type": "string" 16 | }, 17 | "completed": { 18 | "type": "boolean" 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /.eslintrc.js: -------------------------------------------------------------------------------- 1 | // eslint-disable-next-line no-undef 2 | module.exports = { 3 | parser: "@typescript-eslint/parser", 4 | plugins: ["@typescript-eslint"], 5 | parserOptions: { 6 | ecmaVersion: 2017, 7 | sourceType: "module", 8 | }, 9 | extends: [ 10 | "eslint:recommended", 11 | "plugin:@typescript-eslint/eslint-recommended", 12 | "plugin:@typescript-eslint/recommended", 13 | "plugin:prettier/recommended", 14 | ], 15 | rules: { 16 | "@typescript-eslint/interface-name-prefix": 0, 17 | "no-console": 0, 18 | "@typescript-eslint/semi": "warn", 19 | "no-extra-semi": "warn", 20 | }, 21 | }; 22 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "baseUrl": ".", 4 | "removeComments": true, 5 | "moduleResolution": "node", 6 | "noUnusedLocals": true, 7 | "noUnusedParameters": true, 8 | "strictNullChecks": true, 9 | "sourceMap": true, 10 | "target": "es2022", 11 | "outDir": "lib", 12 | "allowSyntheticDefaultImports": true, 13 | "resolveJsonModule": true, 14 | "paths": { 15 | "~/*": ["src/*"] 16 | } 17 | }, 18 | "include": ["src"], 19 | "exclude": [ 20 | "node_modules/**/*", 21 | ".serverless/**/*", 22 | "_warmup/**/*", 23 | ".vscode/**/*", 24 | ".dynamodb" 25 | ] 26 | } 27 | -------------------------------------------------------------------------------- /handler.ts: -------------------------------------------------------------------------------- 1 | import "source-map-support/register"; 2 | 3 | // List functions 4 | export { createList } from "./src/actions/list/create-list.action"; 5 | export { deleteList } from "./src/actions/list/delete-list.action"; 6 | export { getList } from "./src/actions/list/get-list.action"; 7 | export { updateList } from "./src/actions/list/update-list.action"; 8 | 9 | // Task functions 10 | export { createTask } from "./src/actions/task/create-task.action"; 11 | export { getTask } from "./src/actions/task/get-task.action"; 12 | export { deleteTask } from "./src/actions/task/delete-task.action"; 13 | export { updateTask } from "./src/actions/task/update-task.action"; 14 | -------------------------------------------------------------------------------- /src/models/list.model.ts: -------------------------------------------------------------------------------- 1 | import { v4 as UUID } from "uuid"; 2 | 3 | export interface IProps { 4 | id?: string; 5 | name: string; 6 | } 7 | 8 | export interface IListInterface extends IProps { 9 | timestamp: number; 10 | } 11 | 12 | export default class ListModel { 13 | private _id: string; 14 | private _name: string; 15 | 16 | constructor({ id = UUID(), name = "" }: IProps) { 17 | this._id = id; 18 | this._name = name; 19 | } 20 | 21 | set id(value: string) { 22 | this._id = value; 23 | } 24 | 25 | get id(): string { 26 | return this._id; 27 | } 28 | 29 | set name(value: string) { 30 | this._name = value; 31 | } 32 | 33 | get name(): string { 34 | return this._name; 35 | } 36 | 37 | toEntityMappings(): IListInterface { 38 | return { 39 | id: this.id, 40 | name: this.name, 41 | timestamp: new Date().getTime(), 42 | }; 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Serverless example with typescript 2 | 3 | AWS serverless(lambda, dynamodb) example(to-do list app) using serverless framework. 4 | 5 | ## Install 6 | 7 | ```shell 8 | npm install 9 | ``` 10 | 11 | ## How to run 12 | 13 | Sample Requests is placed under `/check`. 14 | 15 | ### local 16 | 17 | ```shell 18 | # install dynamodb-local 19 | npm run dynamodb:install 20 | 21 | # run serverless-offline 22 | npm run start:offline 23 | ``` 24 | 25 | ### AWS 26 | 27 | First, set up your AWS settings and run the following command. 28 | 29 | Serverless framework deploy lambda, api gateway, dynamodb and other resources. 30 | 31 | ```shell 32 | npm run deploy:prod 33 | ``` 34 | 35 | ## TODO 36 | - [ ] add sample ui(vue/react/angular..) 37 | - [ ] implements authentication 38 | - [ ] add unit-test 39 | - [ ] add functional-test 40 | 41 | ## Thanks 42 | 43 | - https://levelup.gitconnected.com/creating-a-simple-serverless-application-using-typescript-and-aws-part-1-be2188f5ff93 -------------------------------------------------------------------------------- /ops-handler.ts: -------------------------------------------------------------------------------- 1 | import "source-map-support/register"; 2 | import { 3 | Callback, 4 | CloudWatchLogsDecodedData, 5 | CloudWatchLogsEvent, 6 | CloudWatchLogsHandler, 7 | Context, 8 | } from "aws-lambda"; 9 | import * as zlib from "zlib"; 10 | 11 | // triggered by subscription filter 12 | export const handleApiGatewayLog: CloudWatchLogsHandler = ( 13 | event: CloudWatchLogsEvent, 14 | _context: Context, 15 | callback: Callback 16 | ): void => { 17 | const decoded = Buffer.from(event.awslogs.data, "base64"); 18 | zlib.gunzip(decoded, (e, result) => { 19 | if (e) { 20 | callback(e, null); 21 | } else { 22 | const json: CloudWatchLogsDecodedData = JSON.parse( 23 | result.toString("ascii") 24 | ); 25 | json.logEvents.forEach((event) => { 26 | console.log("detail info", JSON.parse(event.message)); 27 | }); 28 | // TODO instead of logging, do useful things(mail, chat...) 29 | callback(null); 30 | } 31 | }); 32 | }; 33 | 34 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 Mamezou Co., LTD. 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /src/enums/response-message.enum.ts: -------------------------------------------------------------------------------- 1 | export enum ResponseMessage { 2 | CREATE_LIST_SUCCESS = "To-do list successfully created", 3 | CREATE_LIST_FAIL = "To-do list cannot be created", 4 | DELETE_LIST_SUCCESS = "To-do list successfully deleted", 5 | DELETE_LIST_NOTFOUND = "To-do list has already been deleted", 6 | DELETE_LIST_FAIL = "To-do list cannot be deleted", 7 | GET_LIST_SUCCESS = "To-do list successfully retrieved", 8 | GET_LIST_FAIL = "To-do list not found", 9 | UPDATE_LIST_SUCCESS = "To-do list successfully updated", 10 | UPDATE_LIST_FAIL = "To-do list cannot be updated", 11 | CREATE_TASK_SUCCESS = "Task successfully added", 12 | CREATE_TASK_FAIL = "Task could not be added", 13 | DELETE_TASK_SUCCESS = "Task successfully deleted", 14 | DELETE_TASK_NOTFOUND = "Task has already been deleted", 15 | DELETE_TASK_FAIL = "Task could not be deleted", 16 | UPDATE_TASK_SUCCESS = "Task successfully updated", 17 | UPDATE_TASK_FAIL = "Task could not be updated", 18 | GET_TASK_SUCCESS = "Task successfully retrieved", 19 | GET_TASK_FAIL = "Task not found", 20 | ERROR = "Unknown error.", 21 | INVALID_REQUEST = "Invalid Request!", 22 | GET_ITEM_ERROR = "Item does not exist", 23 | } 24 | -------------------------------------------------------------------------------- /src/utils/lambda-handler.ts: -------------------------------------------------------------------------------- 1 | import { APIGatewayEvent, APIGatewayProxyResult, Context } from "aws-lambda"; 2 | import ResponseModel from "src/models/response.model"; 3 | import "source-map-support/register"; 4 | 5 | export type LambdaHandler = ( 6 | event: APIGatewayEvent, 7 | context: Context 8 | ) => Promise; 9 | 10 | export type RequestHandler = ( 11 | body: REQ, 12 | params: QueryParams, 13 | context: Context 14 | ) => Promise; 15 | 16 | export type QueryParams = Record; 17 | 18 | export const wrapAsRequest = ( 19 | handler: RequestHandler 20 | ): LambdaHandler => { 21 | return async ( 22 | event: APIGatewayEvent, 23 | context: Context 24 | ): Promise => { 25 | const requestData: REQ = event.body ? JSON.parse(event.body) : undefined; 26 | const params = Object.keys(event.queryStringParameters || {}).reduce( 27 | (acc, cur) => { 28 | acc[cur] = event.queryStringParameters?.[cur]; 29 | return acc; 30 | }, 31 | {} 32 | ); 33 | const response = await handler(requestData, params, context); 34 | return response.generate(); 35 | }; 36 | }; 37 | -------------------------------------------------------------------------------- /src/utils/util.ts: -------------------------------------------------------------------------------- 1 | import validate from "validate.js/validate"; 2 | 3 | import ResponseModel from "../models/response.model"; 4 | 5 | export const validateRequest = ( 6 | values: INPUT, 7 | constraints: { [key in string]: unknown } 8 | ): Promise => { 9 | return new Promise((resolve, reject) => { 10 | const validation = validate(values, constraints); 11 | if (typeof validation === "undefined") { 12 | resolve(values); 13 | } else { 14 | reject( 15 | new ResponseModel({ validation }, 400, "required fields are missing") 16 | ); 17 | } 18 | }); 19 | }; 20 | 21 | export const createChunks = (data: T[], chunkSize: number): T[][] => { 22 | const urlChunks: T[][] = []; 23 | let batchIterator = 0; 24 | while (batchIterator < data.length) { 25 | urlChunks.push(data.slice(batchIterator, (batchIterator += chunkSize))); 26 | } 27 | return urlChunks; 28 | }; 29 | 30 | export type DatabaseProp = { 31 | listTable: string; 32 | tasksTable: string; 33 | }; 34 | 35 | export const databaseTables = (): DatabaseProp => { 36 | const { LIST_TABLE, TASKS_TABLE } = process.env; 37 | return { 38 | listTable: LIST_TABLE ?? "unknown-list-table", 39 | tasksTable: TASKS_TABLE ?? "unknown-tasks-table", 40 | }; 41 | }; 42 | -------------------------------------------------------------------------------- /src/actions/task/get-task.action.ts: -------------------------------------------------------------------------------- 1 | import "source-map-support/register"; 2 | 3 | import ResponseModel from "~/models/response.model"; 4 | import DatabaseService from "~/services/database.service"; 5 | import { databaseTables, validateRequest } from "~/utils/util"; 6 | import requestConstraints from "~/constraints/task/get.constraint.json"; 7 | import { QueryParams, wrapAsRequest } from "~/utils/lambda-handler"; 8 | import { ResponseMessage } from "~/enums/response-message.enum"; 9 | import { StatusCode } from "~/enums/status-code.enum"; 10 | 11 | const getTaskHandler = async ( 12 | _body: never, 13 | queryParams: QueryParams 14 | ): Promise => { 15 | const databaseService = new DatabaseService(); 16 | const { tasksTable } = databaseTables(); 17 | 18 | try { 19 | await validateRequest(queryParams, requestConstraints); 20 | const { taskId, listId } = queryParams; 21 | const data = await databaseService.getItem({ 22 | key: taskId!, 23 | hash: "listId", 24 | hashValue: listId!, 25 | tableName: tasksTable, 26 | }); 27 | return new ResponseModel( 28 | { ...data.Item }, 29 | StatusCode.OK, 30 | ResponseMessage.GET_TASK_SUCCESS 31 | ); 32 | } catch (error) { 33 | return error instanceof ResponseModel 34 | ? error 35 | : new ResponseModel({}, StatusCode.ERROR, ResponseMessage.GET_TASK_FAIL); 36 | } 37 | }; 38 | 39 | export const getTask = wrapAsRequest(getTaskHandler); 40 | -------------------------------------------------------------------------------- /src/models/response.model.ts: -------------------------------------------------------------------------------- 1 | import { Status } from "../enums/status.enum"; 2 | 3 | type ResponseHeader = { [header: string]: string | number | boolean }; 4 | 5 | interface IResponseBody { 6 | data: any; 7 | message: string; 8 | status?: string; 9 | } 10 | 11 | interface IResponse { 12 | statusCode: number; 13 | headers: ResponseHeader; 14 | body: string; 15 | } 16 | 17 | const STATUS_MESSAGES = { 18 | 200: Status.SUCCESS, 19 | 201: Status.SUCCESS, 20 | 204: Status.SUCCESS, 21 | 400: Status.BAD_REQUEST, 22 | 404: Status.BAD_REQUEST, 23 | 500: Status.ERROR, 24 | }; 25 | 26 | const RESPONSE_HEADERS: ResponseHeader = { 27 | "Content-Type": "application/json", 28 | "Access-Control-Allow-Origin": "*", 29 | "Access-Control-Allow-Credentials": true, 30 | }; 31 | 32 | export default class ResponseModel { 33 | private readonly body: IResponseBody; 34 | 35 | constructor(data = {}, readonly code = 402, message = "") { 36 | this.body = { 37 | data, 38 | message, 39 | status: STATUS_MESSAGES[code], 40 | }; 41 | this.code = code; 42 | } 43 | 44 | setBodyVariable = (variable: string, value: string): void => { 45 | this.body[variable] = value; 46 | }; 47 | 48 | get message(): string { 49 | return this.body.message; 50 | } 51 | 52 | get data(): any { 53 | return this.body.data; 54 | } 55 | 56 | generate = (): IResponse => { 57 | return { 58 | statusCode: this.code, 59 | headers: RESPONSE_HEADERS, 60 | body: JSON.stringify(this.body), 61 | }; 62 | }; 63 | } 64 | -------------------------------------------------------------------------------- /src/models/task.model.ts: -------------------------------------------------------------------------------- 1 | import { v4 as UUID } from "uuid"; 2 | 3 | interface IProps { 4 | id?: string; 5 | listId: string; 6 | description: string; 7 | completed: boolean; 8 | } 9 | 10 | export interface ITaskInterface extends IProps { 11 | timestamp: number; 12 | } 13 | 14 | export default class TaskModel { 15 | private readonly _id: string; 16 | private _listId: string; 17 | private _description: string; 18 | private _completed: boolean; 19 | 20 | constructor({ 21 | id = UUID(), 22 | listId, 23 | description = "", 24 | completed = false, 25 | }: IProps) { 26 | this._id = id; 27 | this._listId = listId; 28 | this._description = description; 29 | this._completed = completed; 30 | } 31 | 32 | get id(): string { 33 | return this._id; 34 | } 35 | 36 | set listId(value: string) { 37 | this._listId = value; 38 | } 39 | 40 | get listId(): string { 41 | return this._listId; 42 | } 43 | 44 | set description(value: string) { 45 | this._description = value; 46 | } 47 | 48 | get description(): string { 49 | return this._description; 50 | } 51 | 52 | set completed(value: boolean) { 53 | this._completed = value; 54 | } 55 | 56 | get completed(): boolean { 57 | return this._completed; 58 | } 59 | 60 | toEntityMapping(): ITaskInterface { 61 | return { 62 | id: this.id, 63 | listId: this.listId, 64 | description: this.description, 65 | completed: this.completed, 66 | timestamp: new Date().getTime(), 67 | }; 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "todo-list", 3 | "version": "1.0.0", 4 | "description": "todo-list app", 5 | "main": "handler.js", 6 | "scripts": { 7 | "deploy:prod": "sls deploy --stage prod", 8 | "package:prod": "sls package --stage prod", 9 | "undeploy:prod": "sls remove --stage prod", 10 | "start:offline": "sls offline start --stage dev", 11 | "start:offline:debug": "SLS_DEBUG=1 sls offline start --stage dev", 12 | "dynamodb:install": "sls dynamodb install", 13 | "lint": "eslint --fix", 14 | "prettier": "prettier -w src" 15 | }, 16 | "dependencies": { 17 | "@aws-sdk/client-dynamodb": "^3.521.0", 18 | "@aws-sdk/lib-dynamodb": "^3.521.0", 19 | "uuid": "^8.3.2", 20 | "validate.js": "^0.13.1" 21 | }, 22 | "devDependencies": { 23 | "@serverless/typescript": "^3.38.0", 24 | "@types/aws-lambda": "^8.10.134", 25 | "@types/node": "^20.11.20", 26 | "@types/uuid": "^9.0.8", 27 | "@typescript-eslint/eslint-plugin": "^7.0.2", 28 | "@typescript-eslint/parser": "^7.0.2", 29 | "esbuild": "^0.20.1", 30 | "eslint": "^8.57.0", 31 | "eslint-config-prettier": "^8.1.0", 32 | "eslint-plugin-prettier": "^3.3.1", 33 | "npm-run-all": "^4.1.5", 34 | "prettier": "^2.2.1", 35 | "serverless": "^3.38.0", 36 | "serverless-api-gateway-throttling": "^2.0.3", 37 | "serverless-dynamodb": "^0.2.50", 38 | "serverless-esbuild": "^1.51.0", 39 | "serverless-offline": "^13.3.3", 40 | "serverless-plugin-aws-alerts": "^1.7.5", 41 | "source-map-support": "^0.5.21", 42 | "ts-node": "^10.9.2", 43 | "typescript": "^5.3.3" 44 | }, 45 | "author": "noboru-kudo", 46 | "license": "MIT" 47 | } 48 | -------------------------------------------------------------------------------- /resources/cloudwatch-alarms.ts: -------------------------------------------------------------------------------- 1 | export default { 2 | // AlertTopic: { 3 | // Type: "AWS::SNS::Topic", 4 | // Properties: { 5 | // TopicName: "${self:service}-${self:custom.stage}-alert-topic", 6 | // DisplayName: "${self:service}-${self:custom.stage} Alert Topic", 7 | // Subscription: [ 8 | // { 9 | // Protocol: "email", 10 | // Endpoint: "${self:custom.notificationMailAddress}", 11 | // }, 12 | // ], 13 | // }, 14 | // } as CloudFormationResource, 15 | ThrottlingFilter: { 16 | DependsOn: ["ApiGatewayLogGroup"], 17 | Type: "AWS::Logs::MetricFilter", 18 | DeletionPolicy: "Delete", 19 | Properties: { 20 | FilterPattern: '{$.status = "429"}', 21 | LogGroupName: "/aws/api-gateway/${self:service}-${self:custom.stage}", 22 | MetricTransformations: [ 23 | { 24 | DefaultValue: 0, 25 | MetricName: "throttlingCount", 26 | MetricNamespace: "${self:service}-${self:custom.stage}", 27 | MetricValue: "1", 28 | }, 29 | ], 30 | }, 31 | }, 32 | ThrottlingAlarm: { 33 | Type: "AWS::CloudWatch::Alarm", 34 | DeletionPolicy: "Delete", 35 | Properties: { 36 | AlarmDescription: 37 | "${self:service}-${self:custom.stage} API Throttling Alarm", 38 | AlarmName: "${self:service}-${self:custom.stage}-apigw-throttling", 39 | AlarmActions: [{ Ref: "AwsAlertsAlarm" }], 40 | ComparisonOperator: "GreaterThanOrEqualToThreshold", 41 | Threshold: 5, 42 | DatapointsToAlarm: 1, 43 | EvaluationPeriods: 1, 44 | MetricName: "throttlingCount", 45 | Namespace: "${self:service}-${self:custom.stage}", 46 | Period: 60, 47 | Statistic: "Sum", 48 | }, 49 | }, 50 | }; 51 | -------------------------------------------------------------------------------- /src/actions/list/create-list.action.ts: -------------------------------------------------------------------------------- 1 | import "source-map-support/register"; 2 | 3 | import ListModel, { IListInterface } from "~/models/list.model"; 4 | import ResponseModel from "~/models/response.model"; 5 | 6 | import DatabaseService from "~/services/database.service"; 7 | import { databaseTables, validateRequest } from "~/utils/util"; 8 | 9 | import requestConstraints from "~/constraints/list/create.constraint.json"; 10 | import { wrapAsRequest } from "~/utils/lambda-handler"; 11 | import { StatusCode } from "~/enums/status-code.enum"; 12 | import { ResponseMessage } from "~/enums/response-message.enum"; 13 | import { PutCommandInput } from "@aws-sdk/lib-dynamodb"; 14 | 15 | const createListHandler = async ( 16 | body: IListInterface 17 | ): Promise => { 18 | try { 19 | await validateRequest(body, requestConstraints); 20 | const databaseService = new DatabaseService(); 21 | 22 | const listModel = new ListModel(body); 23 | const data = listModel.toEntityMappings(); 24 | const params: PutCommandInput = { 25 | TableName: databaseTables().listTable, 26 | Item: { 27 | id: data.id, 28 | name: data.name, 29 | createdAt: data.timestamp, 30 | updatedAt: data.timestamp, 31 | }, 32 | }; 33 | await databaseService.create(params); 34 | return new ResponseModel( 35 | { listId: data.id }, 36 | StatusCode.CREATED, 37 | ResponseMessage.CREATE_LIST_SUCCESS 38 | ); 39 | } catch (error) { 40 | return error instanceof ResponseModel 41 | ? error 42 | : new ResponseModel( 43 | {}, 44 | StatusCode.ERROR, 45 | ResponseMessage.CREATE_LIST_FAIL 46 | ); 47 | } 48 | }; 49 | 50 | export const createList = wrapAsRequest(createListHandler); 51 | -------------------------------------------------------------------------------- /resources/dynamodb-tables.ts: -------------------------------------------------------------------------------- 1 | export default { 2 | ListTable: { 3 | Type: "AWS::DynamoDB::Table", 4 | DeletionPolicy: "Delete", 5 | Properties: { 6 | TableName: "${self:provider.environment.LIST_TABLE}", 7 | AttributeDefinitions: [{ AttributeName: "id", AttributeType: "S" }], 8 | KeySchema: [{ AttributeName: "id", KeyType: "HASH" }], 9 | ProvisionedThroughput: { 10 | ReadCapacityUnits: "${self:custom.tableThroughput}", 11 | WriteCapacityUnits: "${self:custom.tableThroughput}", 12 | }, 13 | }, 14 | }, 15 | TasksTable: { 16 | Type: "AWS::DynamoDB::Table", 17 | DeletionPolicy: "Delete", 18 | Properties: { 19 | TableName: "${self:provider.environment.TASKS_TABLE}", 20 | AttributeDefinitions: [ 21 | { AttributeName: "id", AttributeType: "S" }, 22 | { AttributeName: "listId", AttributeType: "S" }, 23 | ], 24 | KeySchema: [ 25 | { AttributeName: "id", KeyType: "HASH" }, 26 | { AttributeName: "listId", KeyType: "RANGE" }, 27 | ], 28 | ProvisionedThroughput: { 29 | ReadCapacityUnits: "${self:custom.tableThroughput}", 30 | WriteCapacityUnits: "${self:custom.tableThroughput}", 31 | }, 32 | GlobalSecondaryIndexes: [ 33 | { 34 | IndexName: "list_index", 35 | KeySchema: [{ AttributeName: "listId", KeyType: "HASH" }], 36 | Projection: { 37 | // attributes to project into the index 38 | ProjectionType: "ALL", // (ALL | KEYS_ONLY | INCLUDE) 39 | }, 40 | ProvisionedThroughput: { 41 | ReadCapacityUnits: "${self:custom.tableThroughput}", 42 | WriteCapacityUnits: "${self:custom.tableThroughput}", 43 | }, 44 | }, 45 | ], 46 | }, 47 | }, 48 | }; 49 | -------------------------------------------------------------------------------- /src/actions/task/delete-task.action.ts: -------------------------------------------------------------------------------- 1 | import "source-map-support/register"; 2 | 3 | import ResponseModel from "~/models/response.model"; 4 | import DatabaseService from "~/services/database.service"; 5 | import { databaseTables, validateRequest } from "~/utils/util"; 6 | import requestConstraints from "~/constraints/task/delete.constraint.json"; 7 | import { QueryParams, wrapAsRequest } from "~/utils/lambda-handler"; 8 | import { StatusCode } from "~/enums/status-code.enum"; 9 | import { ResponseMessage } from "~/enums/response-message.enum"; 10 | import { DeleteCommandInput } from '@aws-sdk/lib-dynamodb'; 11 | 12 | const deleteTaskHandler = async ( 13 | _body: never, 14 | queryParams: QueryParams 15 | ): Promise => { 16 | const databaseService = new DatabaseService(); 17 | const { tasksTable } = databaseTables(); 18 | 19 | try { 20 | await validateRequest(queryParams, requestConstraints); 21 | const { taskId, listId } = queryParams; 22 | const existsItem = await databaseService.existsItem({ 23 | key: taskId!, 24 | hash: "listId", 25 | hashValue: listId!, 26 | tableName: tasksTable, 27 | }); 28 | if (!existsItem) { 29 | return new ResponseModel( 30 | {}, 31 | StatusCode.NO_CONTENT, 32 | ResponseMessage.DELETE_TASK_NOTFOUND 33 | ); 34 | } 35 | const params: DeleteCommandInput = { 36 | TableName: tasksTable, 37 | Key: { 38 | id: taskId, 39 | listId: listId, 40 | }, 41 | }; 42 | await databaseService.delete(params); 43 | return new ResponseModel( 44 | {}, 45 | StatusCode.NO_CONTENT, 46 | ResponseMessage.DELETE_TASK_SUCCESS 47 | ); 48 | } catch (error) { 49 | return error instanceof ResponseModel 50 | ? error 51 | : new ResponseModel( 52 | {}, 53 | StatusCode.ERROR, 54 | ResponseMessage.DELETE_TASK_FAIL 55 | ); 56 | } 57 | }; 58 | 59 | export const deleteTask = wrapAsRequest(deleteTaskHandler); 60 | -------------------------------------------------------------------------------- /src/actions/list/update-list.action.ts: -------------------------------------------------------------------------------- 1 | import "source-map-support/register"; 2 | 3 | import ResponseModel from "~/models/response.model"; 4 | import DatabaseService from "~/services/database.service"; 5 | import { databaseTables, validateRequest } from "~/utils/util"; 6 | import requestConstraints from "~/constraints/list/update.constraint.json"; 7 | import { wrapAsRequest } from "~/utils/lambda-handler"; 8 | import { StatusCode } from "~/enums/status-code.enum"; 9 | import { ResponseMessage } from "~/enums/response-message.enum"; 10 | import { UpdateCommandInput } from "@aws-sdk/lib-dynamodb"; 11 | 12 | const updateListHandler = async (body: { 13 | listId: string; 14 | name: string; 15 | }): Promise => { 16 | const databaseService = new DatabaseService(); 17 | const { listTable } = databaseTables(); 18 | const { listId, name } = body; 19 | 20 | try { 21 | await Promise.all([ 22 | validateRequest(body, requestConstraints), 23 | databaseService.getItem({ key: listId, tableName: listTable }), 24 | ]); 25 | 26 | const params: UpdateCommandInput = { 27 | TableName: listTable, 28 | Key: { 29 | id: listId, 30 | }, 31 | UpdateExpression: "set #name = :name, updatedAt = :timestamp", 32 | ExpressionAttributeNames: { 33 | "#name": "name", 34 | }, 35 | ExpressionAttributeValues: { 36 | ":name": name, 37 | ":timestamp": new Date().getTime(), 38 | }, 39 | ReturnValues: "UPDATED_NEW", 40 | }; 41 | const results = await databaseService.update(params); 42 | return new ResponseModel( 43 | { ...results.Attributes }, 44 | StatusCode.OK, 45 | ResponseMessage.UPDATE_LIST_SUCCESS 46 | ); 47 | } catch (error) { 48 | return error instanceof ResponseModel 49 | ? error 50 | : new ResponseModel( 51 | {}, 52 | StatusCode.ERROR, 53 | ResponseMessage.UPDATE_LIST_FAIL 54 | ); 55 | } 56 | }; 57 | 58 | export const updateList = wrapAsRequest(updateListHandler); 59 | -------------------------------------------------------------------------------- /src/actions/task/create-task.action.ts: -------------------------------------------------------------------------------- 1 | import "source-map-support/register"; 2 | 3 | import TaskModel, { ITaskInterface } from "~/models/task.model"; 4 | import ResponseModel from "~/models/response.model"; 5 | import DatabaseService from "~/services/database.service"; 6 | import { databaseTables, validateRequest } from "~/utils/util"; 7 | import requestConstraints from "~/constraints/task/create.constraint.json"; 8 | import { wrapAsRequest } from "~/utils/lambda-handler"; 9 | import { StatusCode } from "~/enums/status-code.enum"; 10 | import { ResponseMessage } from "~/enums/response-message.enum"; 11 | import { PutCommandInput } from '@aws-sdk/lib-dynamodb'; 12 | 13 | const createTaskHandler = async ( 14 | body: ITaskInterface 15 | ): Promise => { 16 | const databaseService = new DatabaseService(); 17 | const { listTable, tasksTable } = databaseTables(); 18 | 19 | try { 20 | await Promise.all([ 21 | validateRequest(body, requestConstraints), 22 | databaseService.getItem({ 23 | key: body.listId, 24 | tableName: listTable, 25 | }), 26 | ]); 27 | const taskModel = new TaskModel(body); 28 | const data = taskModel.toEntityMapping(); 29 | 30 | const params: PutCommandInput = { 31 | TableName: tasksTable, 32 | Item: { 33 | id: data.id, 34 | listId: data.listId, 35 | description: data.description, 36 | completed: data.completed, 37 | createdAt: data.timestamp, 38 | updatedAt: data.timestamp, 39 | }, 40 | }; 41 | await databaseService.create(params); 42 | return new ResponseModel( 43 | { taskId: data.id }, 44 | StatusCode.CREATED, 45 | ResponseMessage.CREATE_TASK_SUCCESS 46 | ); 47 | } catch (error) { 48 | return error instanceof ResponseModel 49 | ? error 50 | : new ResponseModel( 51 | {}, 52 | StatusCode.ERROR, 53 | ResponseMessage.CREATE_TASK_FAIL 54 | ); 55 | } 56 | }; 57 | 58 | export const createTask = wrapAsRequest(createTaskHandler); 59 | -------------------------------------------------------------------------------- /src/actions/list/get-list.action.ts: -------------------------------------------------------------------------------- 1 | import "source-map-support/register"; 2 | 3 | import ResponseModel from "~/models/response.model"; 4 | import DatabaseService from "~/services/database.service"; 5 | import { databaseTables, validateRequest } from "~/utils/util"; 6 | import requestConstraints from "~/constraints/list/get.constraint.json"; 7 | import { QueryParams, wrapAsRequest } from "~/utils/lambda-handler"; 8 | import { StatusCode } from "~/enums/status-code.enum"; 9 | import { ResponseMessage } from "~/enums/response-message.enum"; 10 | import { QueryCommandInput } from "@aws-sdk/lib-dynamodb"; 11 | 12 | const getListHandler = async ( 13 | _body: never, 14 | queryParams: QueryParams 15 | ): Promise => { 16 | const databaseService = new DatabaseService(); 17 | const { listTable, tasksTable } = databaseTables(); 18 | 19 | try { 20 | await validateRequest(queryParams, requestConstraints); 21 | const { listId } = queryParams; 22 | const data = await databaseService.getItem({ 23 | key: listId!, 24 | tableName: listTable, 25 | }); 26 | 27 | const params: QueryCommandInput = { 28 | TableName: tasksTable, 29 | IndexName: "list_index", 30 | KeyConditionExpression: "listId = :listIdVal", 31 | ExpressionAttributeValues: { 32 | ":listIdVal": listId, 33 | }, 34 | }; 35 | 36 | const results = await databaseService.query(params); 37 | const tasks = results?.Items?.map((task) => { 38 | return { 39 | id: task.id, 40 | description: task.description, 41 | completed: task.completed, 42 | createdAt: task.createdAt, 43 | updatedAt: task.updatedAt, 44 | }; 45 | }); 46 | 47 | return new ResponseModel( 48 | { 49 | ...data.Item, 50 | taskCount: tasks?.length, 51 | tasks: tasks, 52 | }, 53 | StatusCode.OK, 54 | ResponseMessage.GET_LIST_SUCCESS 55 | ); 56 | } catch (error) { 57 | return error instanceof ResponseModel 58 | ? error 59 | : new ResponseModel({}, StatusCode.ERROR, ResponseMessage.GET_LIST_FAIL); 60 | } 61 | }; 62 | 63 | export const getList = wrapAsRequest(getListHandler); 64 | -------------------------------------------------------------------------------- /check/rest-api.http: -------------------------------------------------------------------------------- 1 | ### test POST /list 2 | POST {{baseUrl}}/list 3 | Content-Type: application/json 4 | 5 | { 6 | "name": "test" 7 | } 8 | 9 | > {% 10 | client.test("status=201", function () { 11 | client.assert(response.status === 201, "status code error") 12 | client.global.set("listId", response.body.data.listId) 13 | }) 14 | %} 15 | 16 | ### test GET /list 17 | GET {{baseUrl}}/list?listId={{listId}} 18 | 19 | > {% 20 | client.test("status=200", function () { 21 | client.assert(response.status === 200, "status code error") 22 | }) 23 | %} 24 | 25 | ### test PUT /list 26 | PUT {{baseUrl}}/list 27 | Content-Type: application/json 28 | 29 | {"name":"test-update","listId":"{{listId}}"} 30 | 31 | > {% 32 | client.test("status=200", function() { 33 | client.assert(response.status === 200, "status code error") 34 | }) 35 | %} 36 | 37 | ### test POST /task 38 | POST {{baseUrl}}/task 39 | 40 | { 41 | "listId":"{{listId}}", 42 | "description":"test-description", 43 | "completed":false 44 | } 45 | 46 | > {% 47 | client.test("status=201", function () { 48 | client.assert(response.status === 201, "status code error") 49 | client.global.set("taskId", response.body.data.taskId) 50 | }) 51 | %} 52 | 53 | ### test GET /task 54 | GET {{baseUrl}}/task?listId={{listId}}&taskId={{taskId}} 55 | 56 | > {% 57 | client.test("status=200", function () { 58 | client.assert(response.status === 200, "status code error") 59 | }) 60 | %} 61 | 62 | ### test PUT /task 63 | PUT {{baseUrl}}/task 64 | 65 | { 66 | "listId":"{{listId}}", 67 | "taskId":"{{taskId}}", 68 | "description": "updated task", 69 | "completed": true 70 | } 71 | 72 | > {% 73 | client.test("status=200", function () { 74 | client.assert(response.status === 200, "status code error") 75 | }) 76 | %} 77 | 78 | ### test DELETE /task 79 | DELETE {{baseUrl}}/task?listId={{listId}}&taskId={{taskId}} 80 | 81 | { 82 | "listId":"{{listId}}", 83 | "taskId":"{{taskId}}" 84 | } 85 | 86 | > {% 87 | client.test("status=204", function () { 88 | client.assert(response.status === 204, "status code error") 89 | }) 90 | %} 91 | 92 | ### test DELETE /list 93 | DELETE {{baseUrl}}/list?listId={{listId}} 94 | 95 | > {% 96 | client.test("status=204", function () { 97 | client.assert(response.status === 204, "status code error") 98 | }) 99 | %} 100 | 101 | -------------------------------------------------------------------------------- /resources/functions.ts: -------------------------------------------------------------------------------- 1 | export default { 2 | createList: { 3 | handler: "handler.createList", 4 | events: [ 5 | { 6 | http: { 7 | method: "POST", 8 | path: "list", 9 | cors: true, 10 | throttling: { 11 | maxRequestsPerSecond: 2, 12 | maxConcurrentRequests: 1, 13 | }, 14 | }, 15 | }, 16 | ], 17 | }, 18 | deleteList: { 19 | handler: "handler.deleteList", 20 | events: [ 21 | { 22 | http: { 23 | method: "DELETE", 24 | path: "list", 25 | cors: true, 26 | }, 27 | }, 28 | ], 29 | }, 30 | getList: { 31 | handler: "handler.getList", 32 | events: [ 33 | { 34 | http: { 35 | method: "GET", 36 | path: "list", 37 | cors: true, 38 | }, 39 | }, 40 | ], 41 | }, 42 | updateList: { 43 | handler: "handler.updateList", 44 | events: [ 45 | { 46 | http: { 47 | method: "PUT", 48 | path: "list", 49 | cors: true, 50 | }, 51 | }, 52 | ], 53 | }, 54 | createTask: { 55 | handler: "handler.createTask", 56 | events: [ 57 | { 58 | http: { 59 | method: "POST", 60 | path: "task", 61 | cors: true, 62 | }, 63 | }, 64 | ], 65 | }, 66 | deleteTask: { 67 | handler: "handler.deleteTask", 68 | events: [ 69 | { 70 | http: { 71 | method: "DELETE", 72 | path: "task", 73 | cors: true, 74 | }, 75 | }, 76 | ], 77 | }, 78 | getTask: { 79 | handler: "handler.getTask", 80 | events: [ 81 | { 82 | http: { 83 | method: "GET", 84 | path: "task", 85 | cors: true, 86 | }, 87 | }, 88 | ], 89 | }, 90 | updateTask: { 91 | handler: "handler.updateTask", 92 | events: [ 93 | { 94 | http: { 95 | method: "PUT", 96 | path: "task", 97 | cors: true, 98 | }, 99 | }, 100 | ], 101 | }, 102 | handleApiGatewayLog: { 103 | handler: "ops-handler.handleApiGatewayLog", 104 | events: [ 105 | { 106 | cloudwatchLog: { 107 | logGroup: "/aws/api-gateway/${self:service}-${self:custom.stage}", 108 | filter: '{$.status = "429" || $.status = "502" || $.status = "504"}', 109 | }, 110 | }, 111 | ], 112 | }, 113 | }; 114 | -------------------------------------------------------------------------------- /src/actions/task/update-task.action.ts: -------------------------------------------------------------------------------- 1 | import "source-map-support/register"; 2 | 3 | import ResponseModel from "~/models/response.model"; 4 | import DatabaseService from "~/services/database.service"; 5 | import { databaseTables, validateRequest } from "~/utils/util"; 6 | import requestConstraints from "~/constraints/task/update.constraint.json"; 7 | import { wrapAsRequest } from "~/utils/lambda-handler"; 8 | import { StatusCode } from "~/enums/status-code.enum"; 9 | import { ResponseMessage } from "~/enums/response-message.enum"; 10 | import { UpdateCommandInput } from "@aws-sdk/lib-dynamodb"; 11 | 12 | const updateTaskHandler = async (body: { 13 | listId: string; 14 | taskId: string; 15 | completed: string; 16 | description: string; 17 | }): Promise => { 18 | const databaseService = new DatabaseService(); 19 | const { listId, taskId, completed, description } = body; 20 | const { listTable, tasksTable } = databaseTables(); 21 | 22 | try { 23 | await Promise.all([ 24 | validateRequest(body, requestConstraints), 25 | databaseService.getItem({ key: listId, tableName: listTable }), 26 | ]); 27 | const isCompletedPresent = typeof completed !== "undefined"; 28 | 29 | const updateExpression = `set ${ 30 | description ? "description = :description," : "" 31 | } ${ 32 | typeof completed !== "undefined" ? "completed = :completed," : "" 33 | } updatedAt = :timestamp`; 34 | 35 | if (description || isCompletedPresent) { 36 | const params: UpdateCommandInput = { 37 | TableName: tasksTable, 38 | Key: { 39 | id: taskId, 40 | listId: listId, 41 | }, 42 | UpdateExpression: updateExpression, 43 | ExpressionAttributeValues: { 44 | ":timestamp": new Date().getTime(), 45 | }, 46 | ReturnValues: "UPDATED_NEW", 47 | }; 48 | if (description) { 49 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion 50 | params.ExpressionAttributeValues![":description"] = description; 51 | } 52 | if (isCompletedPresent) { 53 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion 54 | params.ExpressionAttributeValues![":completed"] = completed; 55 | } 56 | 57 | const results = await databaseService.update(params); 58 | return new ResponseModel( 59 | { ...results.Attributes }, 60 | StatusCode.OK, 61 | ResponseMessage.UPDATE_TASK_SUCCESS 62 | ); 63 | } else { 64 | return new ResponseModel( 65 | {}, 66 | StatusCode.BAD_REQUEST, 67 | ResponseMessage.INVALID_REQUEST 68 | ); 69 | } 70 | } catch (error) { 71 | return error instanceof ResponseModel 72 | ? error 73 | : new ResponseModel( 74 | {}, 75 | StatusCode.ERROR, 76 | ResponseMessage.UPDATE_TASK_FAIL 77 | ); 78 | } 79 | }; 80 | 81 | export const updateTask = wrapAsRequest(updateTaskHandler); 82 | -------------------------------------------------------------------------------- /src/actions/list/delete-list.action.ts: -------------------------------------------------------------------------------- 1 | import "source-map-support/register"; 2 | 3 | import ResponseModel from "~/models/response.model"; 4 | import { createChunks, databaseTables, validateRequest } from "~/utils/util"; 5 | import requestConstraints from "~/constraints/list/get.constraint.json"; 6 | import { QueryParams, wrapAsRequest } from "~/utils/lambda-handler"; 7 | import { StatusCode } from "~/enums/status-code.enum"; 8 | import { ResponseMessage } from "~/enums/response-message.enum"; 9 | import DatabaseService from "~/services/database.service"; 10 | import { DeleteCommandInput, QueryCommandInput } from "@aws-sdk/lib-dynamodb"; 11 | 12 | const deleteListHandler = async ( 13 | _body: never, 14 | queryParams: QueryParams 15 | ): Promise => { 16 | const { listTable, tasksTable } = databaseTables(); 17 | const databaseService = new DatabaseService(); 18 | 19 | try { 20 | await validateRequest(queryParams, requestConstraints); 21 | const { listId } = queryParams; 22 | 23 | // check item exists 24 | const existsItem = await databaseService.existsItem({ 25 | key: listId!, 26 | tableName: listTable, 27 | }); 28 | if (!existsItem) { 29 | return new ResponseModel( 30 | {}, 31 | StatusCode.NO_CONTENT, 32 | ResponseMessage.DELETE_LIST_NOTFOUND 33 | ); 34 | } 35 | 36 | const params: DeleteCommandInput = { 37 | TableName: listTable, 38 | Key: { id: listId }, 39 | }; 40 | await databaseService.delete(params); // Delete to-do list 41 | 42 | const taskParams: QueryCommandInput = { 43 | TableName: tasksTable, 44 | IndexName: "list_index", 45 | KeyConditionExpression: "listId = :listIdVal", 46 | ExpressionAttributeValues: { 47 | ":listIdVal": listId, 48 | }, 49 | }; 50 | const results = await databaseService.query(taskParams); 51 | 52 | if (results?.Items && results?.Items.length) { 53 | const taskEntities = results?.Items?.map((item) => { 54 | return { DeleteRequest: { Key: { id: item.id } } }; 55 | }); 56 | 57 | if (taskEntities.length > 25) { 58 | const taskChunks = createChunks(taskEntities, 25); 59 | await Promise.all( 60 | taskChunks.map((tasks) => { 61 | return databaseService.batchCreate({ 62 | RequestItems: { 63 | [tasksTable]: tasks, 64 | }, 65 | }); 66 | }) 67 | ); 68 | } else { 69 | await databaseService.batchCreate({ 70 | RequestItems: { 71 | [tasksTable]: taskEntities, 72 | }, 73 | }); 74 | } 75 | } 76 | return new ResponseModel( 77 | {}, 78 | StatusCode.NO_CONTENT, 79 | ResponseMessage.DELETE_LIST_SUCCESS 80 | ); 81 | } catch (error) { 82 | return error instanceof ResponseModel 83 | ? error 84 | : new ResponseModel( 85 | {}, 86 | StatusCode.ERROR, 87 | ResponseMessage.DELETE_LIST_FAIL 88 | ); 89 | } 90 | }; 91 | 92 | export const deleteList = wrapAsRequest(deleteListHandler); 93 | -------------------------------------------------------------------------------- /src/services/database.service.ts: -------------------------------------------------------------------------------- 1 | import ResponseModel from "../models/response.model"; 2 | 3 | import { StatusCode } from "../enums/status-code.enum"; 4 | import { ResponseMessage } from "../enums/response-message.enum"; 5 | 6 | import { DynamoDBClient, DynamoDBClientConfig } from "@aws-sdk/client-dynamodb"; 7 | import { 8 | BatchWriteCommand, 9 | BatchWriteCommandInput, 10 | BatchWriteCommandOutput, 11 | DeleteCommand, 12 | DeleteCommandInput, 13 | DeleteCommandOutput, 14 | DynamoDBDocumentClient, 15 | GetCommand, 16 | GetCommandInput, 17 | GetCommandOutput, 18 | PutCommand, 19 | PutCommandInput, 20 | PutCommandOutput, 21 | QueryCommand, 22 | QueryCommandInput, 23 | QueryCommandOutput, 24 | UpdateCommand, 25 | UpdateCommandInput, 26 | UpdateCommandOutput, 27 | } from "@aws-sdk/lib-dynamodb"; 28 | 29 | type Item = Record; 30 | 31 | const { STAGE } = process.env; 32 | const config: DynamoDBClientConfig = { 33 | region: "ap-northeast-1", 34 | }; 35 | 36 | if (STAGE === "dev") { 37 | config.credentials = { 38 | accessKeyId: "dummy", 39 | secretAccessKey: "dummy", 40 | }; 41 | config.endpoint = "http://localhost:8008"; 42 | console.log("dynamodb-local mode", config); 43 | } else { 44 | console.log("running dynamodb on aws", STAGE); 45 | } 46 | 47 | const dynamodbClient = new DynamoDBClient(config); 48 | const documentClient = DynamoDBDocumentClient.from(dynamodbClient); 49 | 50 | export default class DatabaseService { 51 | getItem = async ({ 52 | key, 53 | hash, 54 | hashValue, 55 | tableName, 56 | }: Item): Promise => { 57 | const params = { 58 | TableName: tableName, 59 | Key: { 60 | id: key, 61 | }, 62 | }; 63 | if (hash) { 64 | params.Key[hash] = hashValue; 65 | } 66 | const results = await this.get(params); 67 | if (Object.keys(results).length) { 68 | return results; 69 | } 70 | console.log("item does not exist"); 71 | throw new ResponseModel( 72 | { id: key }, 73 | StatusCode.NOT_FOUND, 74 | ResponseMessage.GET_ITEM_ERROR 75 | ); 76 | }; 77 | 78 | existsItem = async ({ 79 | key, 80 | hash, 81 | hashValue, 82 | tableName, 83 | }: Item): Promise => { 84 | try { 85 | await this.getItem({ key, hash, hashValue, tableName }); 86 | return true; 87 | } catch (e) { 88 | if (e instanceof ResponseModel) { 89 | return e.code !== StatusCode.NOT_FOUND; 90 | } else { 91 | throw e; 92 | } 93 | } 94 | }; 95 | 96 | create = async (params: PutCommandInput): Promise => { 97 | try { 98 | return await documentClient.send(new PutCommand(params)); 99 | } catch (error) { 100 | console.error("create-error", error); 101 | throw new ResponseModel({}, StatusCode.ERROR, `create-error: ${error}`); 102 | } 103 | }; 104 | 105 | batchCreate = async ( 106 | params: BatchWriteCommandInput 107 | ): Promise => { 108 | try { 109 | return await documentClient.send(new BatchWriteCommand(params)); 110 | } catch (error) { 111 | throw new ResponseModel( 112 | {}, 113 | StatusCode.ERROR, 114 | `batch-write-error: ${error}` 115 | ); 116 | } 117 | }; 118 | 119 | update = async (params: UpdateCommandInput): Promise => { 120 | try { 121 | return await documentClient.send(new UpdateCommand(params)); 122 | } catch (error) { 123 | throw new ResponseModel({}, StatusCode.ERROR, `update-error: ${error}`); 124 | } 125 | }; 126 | 127 | query = async (params: QueryCommandInput): Promise => { 128 | try { 129 | return await documentClient.send(new QueryCommand(params)); 130 | } catch (error) { 131 | throw new ResponseModel({}, StatusCode.ERROR, `query-error: ${error}`); 132 | } 133 | }; 134 | 135 | get = async (params: GetCommandInput): Promise => { 136 | try { 137 | return await documentClient.send(new GetCommand(params)); 138 | } catch (error) { 139 | throw new ResponseModel({}, StatusCode.ERROR, `get-error: ${error}`); 140 | } 141 | }; 142 | 143 | delete = async (params: DeleteCommandInput): Promise => { 144 | try { 145 | return await documentClient.send(new DeleteCommand(params)); 146 | } catch (error) { 147 | throw new ResponseModel({}, StatusCode.ERROR, `delete-error: ${error}`); 148 | } 149 | }; 150 | } 151 | -------------------------------------------------------------------------------- /serverless.ts: -------------------------------------------------------------------------------- 1 | import type { AWS } from "@serverless/typescript"; 2 | import dynamoDbTables from "./resources/dynamodb-tables"; 3 | import cloudwatchAlarms from "./resources/cloudwatch-alarms"; 4 | import functions from "./resources/functions"; 5 | 6 | const serverlessConfiguration: AWS = { 7 | service: "todo-list", 8 | frameworkVersion: "3", 9 | plugins: [ 10 | "serverless-esbuild", 11 | "serverless-dynamodb", 12 | "serverless-offline", 13 | "serverless-api-gateway-throttling", 14 | "serverless-plugin-aws-alerts", 15 | ], 16 | package: { 17 | individually: true, 18 | }, 19 | provider: { 20 | name: "aws", 21 | runtime: "nodejs20.x", 22 | stage: "dev", 23 | region: "ap-northeast-1", 24 | logs: { 25 | restApi: { 26 | accessLogging: true, 27 | format: `{ 28 | "stage" : "$context.stage", 29 | "requestId" : "$context.requestId", 30 | "apiId" : "$context.apiId", 31 | "resource_path" : "$context.resourcePath", 32 | "resourceId" : "$context.resourceId", 33 | "http_method" : "$context.httpMethod", 34 | "sourceIp" : "$context.identity.sourceIp", 35 | "userAgent" : "$context.identity.userAgent", 36 | "caller" : "$context.identity.caller", 37 | "user" : "$context.identity.user", 38 | "requestTime": "$context.requestTime", 39 | "status": "$context.status" 40 | }`.replace(/(\r\n|\n)/gm, ""), 41 | executionLogging: true, 42 | level: "ERROR", 43 | fullExecutionData: false, 44 | }, 45 | frameworkLambda: true, 46 | }, 47 | apiGateway: { 48 | shouldStartNameWithService: true, 49 | minimumCompressionSize: 1024, 50 | }, 51 | environment: { 52 | AWS_NODEJS_CONNECTION_REUSE_ENABLED: "1", 53 | REGION: "${self:custom.region}", 54 | STAGE: "${self:custom.stage}", 55 | LIST_TABLE: "${self:custom.listTable}", 56 | TASKS_TABLE: "${self:custom.tasksTable}", 57 | }, 58 | iam: { 59 | role: { 60 | statements: [ 61 | { 62 | Effect: "Allow", 63 | Action: [ 64 | "dynamodb:DescribeTable", 65 | "dynamodb:Query", 66 | "dynamodb:Scan", 67 | "dynamodb:GetItem", 68 | "dynamodb:PutItem", 69 | "dynamodb:UpdateItem", 70 | "dynamodb:DeleteItem", 71 | ], 72 | Resource: [ 73 | { "Fn::GetAtt": ["ListTable", "Arn"] }, 74 | { "Fn::GetAtt": ["TasksTable", "Arn"] }, 75 | { 76 | "Fn::Join": [ 77 | "/", 78 | [ 79 | { "Fn::GetAtt": ["TasksTable", "Arn"] }, 80 | "index", 81 | "list_index", 82 | ], 83 | ], 84 | }, 85 | ], 86 | }, 87 | ], 88 | }, 89 | }, 90 | }, 91 | custom: { 92 | region: "${opt:region, self:provider.region}", 93 | stage: "${opt:stage, self:provider.stage}", 94 | notificationMailAddress: "${opt:mail, 'noboru-kudo@mamezou.com'}", 95 | listTable: "${self:service}-list-table-${opt:stage, self:provider.stage}", 96 | tasksTable: "${self:service}-tasks-table-${opt:stage, self:provider.stage}", 97 | tableThroughputs: { 98 | prod: 5, 99 | default: 1, 100 | }, 101 | tableThroughput: 102 | "${self:custom.tableThroughputs.${self:custom.stage}, self:custom.tableThroughputs.default}", 103 | dynamodb: { 104 | stages: ["dev"], 105 | start: { 106 | port: 8008, 107 | inMemory: true, 108 | heapInitial: "200m", 109 | heapMax: "1g", 110 | migrate: true, 111 | seed: true, 112 | convertEmptyValues: true, 113 | }, 114 | }, 115 | esbuild: { 116 | bundle: true, 117 | minify: true, 118 | sourcemap: true, 119 | exclude: ["aws-sdk"], 120 | target: "node20", 121 | define: { "require.resolve": undefined }, 122 | platform: "node", 123 | concurrency: 10, 124 | }, 125 | "serverless-offline": { 126 | httpPort: 3000, 127 | babelOptions: { 128 | presets: ["env"], 129 | }, 130 | }, 131 | apiGatewayThrottling: { 132 | maxRequestsPerSecond: 10, 133 | maxConcurrentRequests: 5, 134 | }, 135 | alerts: { 136 | stages: ["dev", "prod"], 137 | topics: { 138 | alarm: { 139 | topic: "${self:service}-${self:custom.stage}-alerts-alarm", 140 | notifications: [ 141 | { 142 | protocol: "email", 143 | endpoint: "${self:custom.notificationMailAddress}", 144 | }, 145 | ], 146 | }, 147 | }, 148 | alarms: ["functionErrors", "functionThrottles"], 149 | }, 150 | }, 151 | functions, 152 | resources: { 153 | Resources: { 154 | ...dynamoDbTables, 155 | ...cloudwatchAlarms, 156 | }, 157 | }, 158 | }; 159 | 160 | module.exports = serverlessConfiguration; 161 | --------------------------------------------------------------------------------