-
Notifications
You must be signed in to change notification settings - Fork 0
/
taskRepository.ts
94 lines (83 loc) · 2.41 KB
/
taskRepository.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
import { getConfig } from '@config';
import {
TaskDatabase,
taskDatabaseSchema,
} from '@app/schemas/taskDatabaseSchema';
import { DeleteCommand, PutCommand, QueryCommand } from '@aws-sdk/lib-dynamodb';
import { createDynamoDbDocumentClient } from '@app/database/createDynamoDbDocumentClient';
const tableName = getConfig().dynamoDb.tableName;
const createTaskFromDatabaseRecord = (record: {
[key: string]: unknown;
}): TaskDatabase => {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { principalId, ...recordWithoutPrincipalId } = record;
return taskDatabaseSchema.parse(recordWithoutPrincipalId);
};
export const getTask = async (
principalId: string,
id: string,
): Promise<TaskDatabase> => {
const queryCommand = new QueryCommand({
TableName: tableName,
ExpressionAttributeNames: {
'#id': 'id',
'#principalId': 'principalId',
},
ExpressionAttributeValues: {
':id': id,
':principalId': principalId,
},
KeyConditionExpression: '#principalId = :principalId and #id = :id',
});
const data = await createDynamoDbDocumentClient().send(queryCommand);
if (!data || !data.Items || data.Count === 0) {
throw new Error('Item not found.');
}
return createTaskFromDatabaseRecord(data.Items[0]);
};
export const deleteTask = async (
principalId: string,
id: string,
): Promise<void> => {
const deleteCommand = new DeleteCommand({
TableName: tableName,
Key: {
id,
principalId,
},
});
await createDynamoDbDocumentClient().send(deleteCommand);
};
export const addTask = async (
principalId: string,
task: TaskDatabase,
): Promise<void> => {
const putCommand = new PutCommand({
Item: {
...task,
principalId,
},
TableName: tableName,
});
await createDynamoDbDocumentClient().send(putCommand);
};
export const getAllTasks = async (
principalId: string,
): Promise<TaskDatabase[]> => {
const queryCommand = new QueryCommand({
TableName: tableName,
ExpressionAttributeNames: {
'#principalId': 'principalId',
},
ExpressionAttributeValues: {
':principalId': principalId,
},
KeyConditionExpression: '#principalId = :principalId',
});
const data = await createDynamoDbDocumentClient().send(queryCommand);
console.log('data', data);
if (!data || !data.Items || data.Count === 0) {
return [];
}
return data.Items.map(createTaskFromDatabaseRecord);
};