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
|
import { databaseTimeToDate } from '$lib/Utility/time';
import { sql } from '@vercel/postgres';
export interface Badge {
post?: string;
image?: string;
description?: string;
id?: number;
time?: string;
category?: string;
}
export const getUserBadges = async (userId: number): Promise<Badge[]> => {
return (await sql`SELECT * FROM user_badges WHERE user_id = ${userId};`).rows.sort((a, b) =>
databaseTimeToDate((a as Badge).time ?? '').getTime() >
databaseTimeToDate((b as Badge).time ?? '').getTime()
? -1
: 1
) as Badge[];
};
export const addUserBadge = async (userId: number, badge: Badge) => {
const { post, image, description, time, category } = badge;
if (post === undefined || image === undefined) return;
if (time) {
(
await sql`INSERT INTO user_badges (user_id, post, image, description, time, category) VALUES (${userId}, ${post}, ${image}, ${
description || null
}, ${time}, ${category || null});`
).rows;
} else {
(
await sql`INSERT INTO user_badges (user_id, post, image, description, category) VALUES (${userId}, ${post}, ${image}, ${
description || null
}, ${category || null});`
).rows;
}
};
export const removeUserBadge = async (userId: number, id: number) => {
if (!isNaN(id)) await sql`DELETE FROM user_badges WHERE user_id = ${userId} AND id = ${id};`;
};
export const updateUserBadge = async (userId: number, id: number, badge: Badge) => {
if (badge.post === undefined || badge.image === undefined || badge.description === undefined)
return;
await sql`
UPDATE user_badges SET post = ${badge.post || null}, image = ${
badge.image || null
}, description = ${badge.description || null}, category = ${
badge.category || null
} WHERE id = ${id} AND user_id = ${userId};`;
};
|