aboutsummaryrefslogtreecommitdiff
path: root/src/lib/Database/SB/User/configuration.ts
blob: b889e95ca71295214983bee8ef87f246566324e4 (plain) (blame)
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
import sb from '../../sb';

interface UserConfiguration {
	user_id: number;
	configuration: object;
	created_at: string;
	updated_at: string;
}

interface NewUserConfiguration {
	configuration: object;
	updated_at?: string;
}

export const getUserConfiguration = async (userId: number) => {
	const { data, error } = await sb.from('user_configuration').select('*').eq('user_id', userId);

	if (error || data.length === 0 || data[0].user_id !== userId) return null;

	return data[0] as UserConfiguration;
};

export const setUserConfiguration = async (userId: number, configuration: NewUserConfiguration) => {
	const { data, error } = await sb
		.from('user_configuration')
		.upsert(
			{
				user_id: userId,
				configuration: configuration.configuration,
				updated_at: configuration.updated_at || new Date().toISOString()
			},
			{ onConflict: 'user_id' }
		)
		.select();

	if (error || !data || (data as []).length === 0) return null;

	return data[0].configuration as UserConfiguration;
};

export const deleteUserConfiguration = async (userId: number) => {
	const { data, error } = await sb.from('user_configuration').delete().eq('user_id', userId);

	if (error || !data) return null;

	return data;
};