1 | import { createClient, SupabaseClient } from "@supabase/[email protected]" |
2 |
|
3 | |
4 | * @param filter Learn more at https://supabase.com/docs/reference/javascript/filter |
5 | * |
6 | * @param token Supabase `access_token` and `refresh_token`. `expires_at` (optional) is a UNIX |
7 | * timestamp in seconds. |
8 | * |
9 | * @param count Count algorithm to use to count rows in the table or view. |
10 | * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the hood. |
11 | * `"planned"`: Approximated but fast count algorithm. Uses the Postgres statistics under the hood. |
12 | * `"estimated"`: Uses exact count for low numbers and planned count for high numbers. |
13 | */ |
14 | type Supabase = { |
15 | url: string; |
16 | key: string; |
17 | }; |
18 | export async function main( |
19 | auth: Supabase, |
20 | table: string, |
21 | filter: { |
22 | column: string; |
23 | operator: string; |
24 | value: any; |
25 | }, |
26 | return_deleted: boolean = false, |
27 | token?: { |
28 | access: string; |
29 | refresh: string; |
30 | expires_at?: number; |
31 | }, |
32 | count?: "exact" | "planned" | "estimated", |
33 | ) { |
34 | return await refreshAndRetryIfExpired(auth, token, async (client) => { |
35 | let query: any = client |
36 | .from(table) |
37 | .delete({ count }) |
38 | .filter(filter.column, filter.operator, filter.value); |
39 |
|
40 | if (return_deleted) { |
41 | query = query.select(); |
42 | } |
43 |
|
44 | return query; |
45 | }); |
46 | } |
47 |
|
48 | async function refreshAndRetryIfExpired( |
49 | auth: { url: string; key: string }, |
50 | token: { access: string; refresh: string; expires_at?: number } | undefined, |
51 | fn: (client: SupabaseClient) => Promise<{ data: any; error?: any }>, |
52 | ): Promise<{ data: any; error?: any; token?: { access: string; refresh: string; expires_at?: number } }> { |
53 | const makeClient = async (autoRefreshToken: boolean) => { |
54 | const client = createClient(auth.url, auth.key, { |
55 | auth: { autoRefreshToken, persistSession: false }, |
56 | }) |
57 | if (token) { |
58 | await client.auth.setSession({ access_token: token.access, refresh_token: token.refresh }) |
59 | } |
60 | return client |
61 | } |
62 | try { |
63 | let result = await fn(await makeClient(false)) |
64 | if (result?.error?.code === "PGRST301" && token) { |
65 | const client = await makeClient(true) |
66 | result = await fn(client) |
67 | const { data } = await client.auth.getSession() |
68 | if (data?.session) { |
69 | token = { |
70 | access: data.session.access_token, |
71 | refresh: data.session.refresh_token, |
72 | expires_at: data.session.expires_at, |
73 | } |
74 | } |
75 | } |
76 | return { ...result, token } |
77 | } catch (error) { |
78 | return { data: null, error } |
79 | } |
80 | } |
81 |
|