aboutsummaryrefslogtreecommitdiff
path: root/src/lib/Database/userConfiguration.ts
blob: 6a22105af1d41971dc100fca88b5bd736a39bbcd (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
48
49
50
import supabase from './supabase';

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 supabase
		.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 supabase
		.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 supabase.from('user_configuration').delete().eq('user_id', userId);

	if (error || !data) return null;

	return data;
};