Skip to content

Instantly share code, notes, and snippets.

@harryhan24
Forked from apoorvmote/createLambda.ts
Created June 12, 2022 06:02
Show Gist options
  • Save harryhan24/8237d663e49390526b61128a4d650659 to your computer and use it in GitHub Desktop.
Save harryhan24/8237d663e49390526b61128a4d650659 to your computer and use it in GitHub Desktop.
import { APIGatewayProxyEventV2, APIGatewayProxyResultV2 } from "aws-lambda";
import { DynamoDB, PutItemInput } from '@aws-sdk/client-dynamodb'
import { marshall } from '@aws-sdk/util-dynamodb'
import { v4 as uuid } from 'uuid'
interface TodoInput {
id?: string
title: string
done: boolean
}
interface Todo {
id: string
title: string
done: boolean
}
export async function createTodo(event: APIGatewayProxyEventV2): Promise<APIGatewayProxyResultV2> {
const { body } = event
if (!body) {
return sendFail('invalid request')
}
const { id, title, done } = JSON.parse(body) as TodoInput
const dynamoClient = new DynamoDB({
region: 'us-east-1'
})
const newTodo: Todo = {
id: id ?? uuid(),
title, done
}
const todoParams: PutItemInput = {
Item: marshall(newTodo),
TableName: process.env.TODO_TABLE_NAME
}
try {
await dynamoClient.putItem(todoParams)
return {
statusCode: 200,
body: JSON.stringify({ newTodo })
}
} catch (err) {
console.log(err)
return sendFail('something went wrong')
}
}
function sendFail(message: string): APIGatewayProxyResultV2 {
return {
statusCode: 400,
body: JSON.stringify({ message })
}
}
interface TodoInput {
id?: string
owner?: string
title: string
done: boolean
}
interface Todo {
id: string
owner?: string
title: string
done: boolean
}
export async function createTodo(event: APIGatewayProxyEventV2): Promise<APIGatewayProxyResultV2> {
const { body } = event
if (!body) {
return sendFail('invalid request')
}
const { id, owner, title, done } = JSON.parse(body) as TodoInput
const dynamoClient = new DynamoDB({
region: 'us-east-1'
})
const newTodo: Todo = {
id: id ?? uuid(),
owner, title, done
}
const createTodoFn = new NodejsFunction(this, 'createTodoFn', {
runtime: Runtime.NODEJS_14_X,
entry: `${__dirname}/../lambda-fns/create/index.ts`,
handler: 'createTodo',
environment: {
TODO_TABLE_NAME: todoTableName
}
})
todoTable.grantReadWriteData(createTodoFn)
import { APIGatewayProxyEventV2, APIGatewayProxyResultV2 } from "aws-lambda";
import { DynamoDB, DeleteItemInput } from '@aws-sdk/client-dynamodb'
import { marshall, unmarshall } from '@aws-sdk/util-dynamodb'
interface DeleteTodo {
id: string
}
export async function deleteTodo(event: APIGatewayProxyEventV2): Promise<APIGatewayProxyResultV2> {
const { body } = event
if (!body) {
return sendFail('invalid request')
}
const { id } = JSON.parse(body) as DeleteTodo
const dynamoClient = new DynamoDB({
region: 'us-east-1'
})
const todoParams: DeleteItemInput = {
Key: marshall({ id }),
ReturnValues: 'ALL_OLD',
TableName: process.env.TODO_TABLE_NAME
}
try {
const { Attributes } = await dynamoClient.deleteItem(todoParams)
const todo = Attributes ? unmarshall(Attributes) : null
return {
statusCode: 200,
body: JSON.stringify({ todo })
}
} catch (err) {
console.log(err)
return sendFail('something went wrong')
}
}
function sendFail(message: string): APIGatewayProxyResultV2 {
return {
statusCode: 400,
body: JSON.stringify({ message })
}
}
const deleteTodoFn = new NodejsFunction(this, 'deleteTodoFn', {
runtime: Runtime.NODEJS_14_X,
entry: `${__dirname}/../lambda-fns/delete/index.ts`,
handler: 'deleteTodo',
environment: {
TODO_TABLE_NAME: todoTableName
}
})
todoTable.grantReadWriteData(deleteTodoFn)
import { APIGatewayProxyEventV2, APIGatewayProxyResultV2 } from "aws-lambda";
import { DynamoDB, ScanInput } from '@aws-sdk/client-dynamodb'
import { unmarshall } from '@aws-sdk/util-dynamodb'
export async function getAll(event: APIGatewayProxyEventV2): Promise<APIGatewayProxyResultV2> {
const dynamoClient = new DynamoDB({
region: 'us-east-1'
})
const scanTodo: ScanInput = {
TableName: process.env.TODO_TABLE_NAME
}
try {
const { Items } = await dynamoClient.scan(scanTodo)
const userData = Items ? Items.map(item => unmarshall(item)) : []
return {
statusCode: 200,
body: JSON.stringify({ listTodo: userData})
}
} catch (err) {
console.log(err)
return {
statusCode: 400,
body: JSON.stringify({
message: 'something went wrong'
})
}
}
}
const getAllTodoFn = new NodejsFunction(this, 'getAllTodoFn', {
runtime: Runtime.NODEJS_14_X,
entry: `${__dirname}/../lambda-fns/getAll/index.ts`,
handler: 'getAll',
environment: {
TODO_TABLE_NAME: todoTableName
}
})
todoTable.grantReadData(getAllTodoFn)
import { APIGatewayProxyEventV2, APIGatewayProxyResultV2 } from "aws-lambda";
import { DynamoDB, GetItemInput } from '@aws-sdk/client-dynamodb'
import { marshall, unmarshall } from '@aws-sdk/util-dynamodb'
interface UserInput {
id: string
}
export async function getOne(event: APIGatewayProxyEventV2): Promise<APIGatewayProxyResultV2> {
const { body } = event
if (!body) return sendError('invalid request')
const data = JSON.parse(body) as UserInput
const dynamoClient = new DynamoDB({
region: 'us-east-1'
})
const getTodo: GetItemInput = {
Key: marshall({
id: data.id
}),
TableName: process.env.TODO_TABLE_NAME
}
try {
const { Item } = await dynamoClient.getItem(getTodo)
const todo = Item ? unmarshall(Item) : null
return {
statusCode: 200,
body: JSON.stringify({ todo })
}
} catch (err) {
console.log(err)
return sendError('something went wrong')
}
}
function sendError(message: string): APIGatewayProxyResultV2 {
return {
statusCode: 400,
body: JSON.stringify({ message })
}
}
const getOneTodoFn = new NodejsFunction(this, 'getOneTodoFn', {
runtime: Runtime.NODEJS_14_X,
entry: `${__dirname}/../lambda-fns/getOne/index.ts`,
handler: 'getOne',
environment: {
TODO_TABLE_NAME: todoTableName
}
})
todoTable.grantReadData(getOneTodoFn)
todoTable.addGlobalSecondaryIndex({
indexName: 'ownerIndex',
partitionKey: {
name: 'owner',
type: AttributeType.STRING
}
})
import { APIGatewayProxyEventV2, APIGatewayProxyResultV2 } from "aws-lambda";
import { DynamoDB, QueryInput } from '@aws-sdk/client-dynamodb'
import { marshall, unmarshall } from '@aws-sdk/util-dynamodb'
interface UserInput {
owner: string
}
export async function queryTodo(event: APIGatewayProxyEventV2): Promise<APIGatewayProxyResultV2> {
const { body } = event
if (!body) return sendError('invalid request')
const data = JSON.parse(body) as UserInput
const dynamoClient = new DynamoDB({
region: 'us-east-1'
})
const queryTodo: QueryInput = {
KeyConditionExpression: '#todoOwner = :userId',
ExpressionAttributeNames: {
'#todoOwner': 'owner'
},
ExpressionAttributeValues: marshall({
':userId': data.owner
}),
IndexName: 'ownerIndex',
TableName: process.env.TODO_TABLE_NAME
}
try {
const { Items } = await dynamoClient.query(queryTodo)
const listTodo = Items ? Items.map(item => unmarshall(item)) : []
return {
statusCode: 200,
body: JSON.stringify({ listTodo })
}
} catch (err) {
console.log(err)
return sendError('something went wrong')
}
}
function sendError(message: string): APIGatewayProxyResultV2 {
return {
statusCode: 400,
body: JSON.stringify({ message })
}
}
const tableWithIndex = Table.fromTableAttributes(this, 'tableWithIndex', {
tableName: todoTableName,
globalIndexes: ['ownerIndex']
})
const queryTodoFn = new NodejsFunction(this, 'queryTodoFn', {
runtime: Runtime.NODEJS_14_X,
entry: `${__dirname}/../lambda-fns/query/index.ts`,
handler: 'queryTodo',
environment: {
TODO_TABLE_NAME: todoTableName
}
})
tableWithIndex.grantReadData(queryTodoFn)
const todoTable = new Table(this, 'todoTable', {
partitionKey: {
name: 'id',
type: AttributeType.STRING
},
billingMode: BillingMode.PAY_PER_REQUEST,
removalPolicy: RemovalPolicy.DESTROY
})
new CfnOutput(this, 'todoTableName', {
value: todoTable.tableName
})
import { APIGatewayProxyEventV2, APIGatewayProxyResultV2 } from "aws-lambda";
import { DynamoDB, UpdateItemInput } from '@aws-sdk/client-dynamodb'
import { marshall, unmarshall } from '@aws-sdk/util-dynamodb'
interface UpdateTodo {
id: string
done: boolean
}
export async function update(event: APIGatewayProxyEventV2): Promise<APIGatewayProxyResultV2> {
const { body } = event
if (!body) {
return sendFail('invalid request')
}
const { id, done } = JSON.parse(body) as UpdateTodo
const dynamoClient = new DynamoDB({
region: 'us-east-1'
})
const todoParams: UpdateItemInput = {
Key: marshall({ id }),
UpdateExpression: 'set done = :done',
ExpressionAttributeValues: marshall({
':done': done
}),
ReturnValues: 'ALL_NEW',
TableName: process.env.UPDATE_TABLE_NAME
}
try {
const { Attributes } = await dynamoClient.updateItem(todoParams)
const todo = Attributes ? unmarshall(Attributes) : null
return {
statusCode: 200,
body: JSON.stringify({ todo })
}
} catch (err) {
console.log(err)
return sendFail('something went wrong')
}
}
function sendFail(message: string): APIGatewayProxyResultV2 {
return {
statusCode: 400,
body: JSON.stringify({ message })
}
}
const updateTodoFn = new NodejsFunction(this, 'updateTodoFn', {
runtime: Runtime.NODEJS_14_X,
entry: `${__dirname}/../lambda-fns/update/index.ts`,
handler: 'update',
environment: {
TODO_TABLE_NAME: todoTableName
}
})
todoTable.grantReadWriteData(updateTodoFn)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment