-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathboards.ts
More file actions
105 lines (90 loc) · 2.69 KB
/
boards.ts
File metadata and controls
105 lines (90 loc) · 2.69 KB
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
import { supabase } from '../supabase'
import type { BoardRow, InsertBoard, UpdateBoard } from '../../types/database'
import type { DatabaseResponse, QueryOptions, RealtimeCallbacks, SubscriptionResult } from './types'
export async function getAll(userId: string, options?: QueryOptions): Promise<DatabaseResponse<BoardRow[]>> {
let query = supabase
.from('boards')
.select('*')
.eq('user_id', userId)
if (options?.orderBy) {
query = query.order(options.orderBy, { ascending: options.ascending ?? true })
} else {
query = query.order('created_at', { ascending: false })
}
if (options?.limit) {
query = query.limit(options.limit)
}
if (options?.offset) {
query = query.range(options.offset, options.offset + (options.limit ?? 10) - 1)
}
const { data, error } = await query
return { data, error }
}
export async function getById(id: string, userId: string): Promise<DatabaseResponse<BoardRow>> {
const { data, error } = await supabase
.from('boards')
.select('*')
.eq('id', id)
.eq('user_id', userId)
.single()
return { data, error }
}
export async function create(board: InsertBoard): Promise<DatabaseResponse<BoardRow>> {
const { data, error } = await supabase
.from('boards')
.insert(board)
.select()
.single()
return { data, error }
}
export async function update(id: string, updates: UpdateBoard, userId: string): Promise<DatabaseResponse<BoardRow>> {
const { data, error } = await supabase
.from('boards')
.update({ ...updates, updated_at: new Date().toISOString() })
.eq('id', id)
.eq('user_id', userId)
.select()
.single()
return { data, error }
}
export async function deleteBoard(id: string, userId: string): Promise<DatabaseResponse<null>> {
const { data, error } = await supabase
.from('boards')
.delete()
.eq('id', id)
.eq('user_id', userId)
return { data, error }
}
export function subscribe(userId: string, callbacks: RealtimeCallbacks<BoardRow>): SubscriptionResult {
const channel = supabase
.channel('boards-changes')
.on(
'postgres_changes',
{
event: '*',
schema: 'public',
table: 'boards',
filter: `user_id=eq.${userId}`
},
(payload) => {
switch (payload.eventType) {
case 'INSERT':
callbacks.onInsert?.(payload.new as BoardRow)
break
case 'UPDATE':
callbacks.onUpdate?.(payload.new as BoardRow)
break
case 'DELETE':
callbacks.onDelete?.(payload.old as BoardRow)
break
}
}
)
.subscribe()
return {
channel,
unsubscribe: () => {
supabase.removeChannel(channel)
}
}
}