-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathitemRepository.ts
92 lines (73 loc) · 2.56 KB
/
itemRepository.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
import databaseClient, {
type Result,
type Rows,
} from "../../../database/client";
class ItemRepository {
// The C of CRUD - Create operation
async create(item: Omit<Item, "id">) {
// Execute the SQL INSERT query to add a new item to the "item" table
const [result] = await databaseClient.query<Result>(
"insert into item (title, user_id) values (?, ?)",
[item.title, item.user_id],
);
// Return the ID of the newly inserted item
return result.insertId;
}
// The Rs of CRUD - Read operations
async read(id: number) {
// Execute the SQL SELECT query to retrieve a specific item by its ID
const [rows] = await databaseClient.query<Rows>(
"select * from item where id = ? and deleted_at is null",
[id],
);
// Return the first row of the result, which represents the item
return rows[0] as Item | null;
}
async readAll() {
// Execute the SQL SELECT query to retrieve all items from the "item" table
const [rows] = await databaseClient.query<Rows>(
"select * from item where deleted_at is null",
);
// Return the array of items
return rows as Item[];
}
// The U of CRUD - Update operation
async update(id: number, item: Omit<Item, "id">) {
// Execute the SQL UPDATE query to update an existing item in the "item" table
const [result] = await databaseClient.query<Result>(
"update item set title = ?, user_id = ? where id = ?",
[item.title, item.user_id, id],
);
// Return the number of affected rows
return result.affectedRows;
}
// The Ds of CRUD - Delete operations
async softDelete(id: number) {
// Execute the SQL UPDATE query to update an existing item in the "item" table
const [result] = await databaseClient.query<Result>(
"update item set deleted_at = now() where id = ?",
[id],
);
// Return the number of affected rows
return result.affectedRows;
}
async softUndelete(id: number) {
// Execute the SQL UPDATE query to update an existing item in the "item" table
const [result] = await databaseClient.query<Result>(
"update item set deleted_at = null where id = ?",
[id],
);
// Return the number of affected rows
return result.affectedRows;
}
async hardDelete(id: number) {
// Execute the SQL DELETE query to delete a specific item by its ID
const [result] = await databaseClient.query<Result>(
"delete from item where id = ?",
[id],
);
// Return the number of affected rows
return result.affectedRows;
}
}
export default new ItemRepository();