Created
May 22, 2020 16:59
-
-
Save robertofrontado/11e8f7fe4ac131965b37075faee3ae39 to your computer and use it in GitHub Desktop.
serverless-todo-todorepository
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as AWS from 'aws-sdk' | |
import { DocumentClient } from 'aws-sdk/clients/dynamodb' | |
import { TodoItem } from '../models/TodoItem' | |
export default class TodoRepository { | |
constructor( | |
private readonly docClient: DocumentClient = createDynamoDBClient(), | |
private readonly todoTable = process.env.TODOS_TABLE) { | |
} | |
async getAllTodos(): Promise<TodoItem[]> { | |
const result = await this.docClient.scan({ | |
TableName: this.todoTable | |
}).promise() | |
return result.Items as TodoItem[] | |
} | |
async createTodo(todo: TodoItem): Promise<TodoItem> { | |
await this.docClient.put({ | |
TableName: this.todoTable, | |
Item: todo | |
}).promise() | |
return todo | |
} | |
async updateTodo(partialTodo: Partial<TodoItem>): Promise<TodoItem> { | |
const updated = await this.docClient.update({ | |
TableName: this.todoTable, | |
Key: { 'id': partialTodo.id }, | |
UpdateExpression: 'set #name = :name, done = :done', | |
ExpressionAttributeNames: { | |
'#name': 'name' | |
}, | |
ExpressionAttributeValues: { | |
':name': partialTodo.name, | |
':done': partialTodo.done | |
}, | |
ReturnValues: 'ALL_NEW' | |
}).promise() | |
return updated.Attributes as TodoItem | |
} | |
async deleteTodoById(id: string) { | |
return this.docClient.delete({ | |
TableName: this.todoTable, | |
Key: { 'id': id } | |
}).promise() | |
} | |
} | |
function createDynamoDBClient() { | |
if (process.env.IS_OFFLINE) { | |
return new AWS.DynamoDB.DocumentClient({ | |
region: 'localhost', | |
endpoint: 'http://localhost:8000' | |
}) | |
} | |
return new AWS.DynamoDB.DocumentClient() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment