]> git.r.bdr.sh - rbdr/forum/blobdiff - src/lib/stores/supabase.ts
Use supabase
[rbdr/forum] / src / lib / stores / supabase.ts
diff --git a/src/lib/stores/supabase.ts b/src/lib/stores/supabase.ts
new file mode 100644 (file)
index 0000000..804141f
--- /dev/null
@@ -0,0 +1,38 @@
+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));
+    })()
+  });
+}