aboutsummaryrefslogtreecommitdiff
path: root/src/lib/stores/supabase.ts
blob: 5bcd941d14b2cbc0e053fc907fab4f40996c7be8 (plain)
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
import { readable } from 'svelte/store';
import { initialResponse, errorResponse, response } from './response_builder';

import type { Readable } from 'svelte/store';
import type { PostgrestFilterBuilder } from '@supabase/postgrest-js';
import type { StoreState } from './response_builder';

export function collection<T>(
	query: PostgrestFilterBuilder<T>,
	initialValue: T[]
): Readable<StoreState<T[]>> {
	return readable(initialResponse<T[]>(initialValue), (set) => {
		(async function () {
			const { data, error } = await query;

			if (error) {
				return set(errorResponse<T[]>(error));
			}

			set(response<T[]>(data));
		})();
	});
}

export function single<T>(
	query: PostgrestFilterBuilder<T>,
	initialValue: T
): Readable<StoreState<T>> {
	return readable(initialResponse<T>(initialValue), (set) => {
		(async function () {
			const { data, error } = await query.single();

			if (error) {
				return set(errorResponse<T>(error));
			}

			set(response<T>(data));
		})();
	});
}