forked from e2b-dev/E2B
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseLatestDeployment.ts
More file actions
82 lines (71 loc) · 2.69 KB
/
Copy pathuseLatestDeployment.ts
File metadata and controls
82 lines (71 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
import { deployments, projects } from '@prisma/client'
import { useSupabaseClient } from '@supabase/auth-helpers-react'
import { useState, useEffect } from 'react'
import { deploymentsTable } from 'db/tables'
import { Database } from 'db/supabase'
import { Route } from 'state/store'
export function useLatestDeployment(project: projects, route?: Route) {
const [initDeployment, setInitDeployment] = useState<deployments>()
const [deployment, setDeployment] = useState<deployments>()
const client = useSupabaseClient<Database>()
useEffect(function init() {
if (!route?.id) return
(async function () {
// TODO: SECURITY - Enable row security for all tables and secure access to deployments.
const deployment = await client
.from(deploymentsTable)
.select('*')
.eq('project_id', project.id)
.eq('route_id', route.id)
.order('created_at', { ascending: false })
.limit(1)
.single()
if (deployment.error) return
setInitDeployment(deployment.data as unknown as deployments)
}())
}, [client, project.id, route?.id])
// Sometimes a large field from realtime server can be missing because of the internal POSTGRES/TOAST workings.
// We changed the table replication to full with `ALTER TABLE events REPLICA IDENTITY FULL;` to fix this.
// https://github.com/supabase/realtime/issues/223 mentioned that we may need to check the `old_record` field of the payload for the actual value,
// but so far it seems we don't have to.
useEffect(function subscribe() {
if (!route?.id) return
// TODO: SECURITY - Enable row security for all tables and configure access to deployments.
const insertSub = client.channel('any')
.on('postgres_changes',
{
event: 'INSERT',
schema: 'public',
table: deploymentsTable,
filter: `project_id=eq.${project.id}`,
}, payload => {
if (payload.new.route_id === route.id) {
setDeployment(payload.new as deployments)
}
})
.subscribe()
// TODO: SECURITY - Enable row security for all tables and configure access to deployments.
const updateSub = client.channel('any')
.on('postgres_changes',
{
event: 'UPDATE',
schema: 'public',
table: deploymentsTable,
filter: `project_id=eq.${project.id}`,
}, payload => {
if (payload.new.route_id === route.id) {
setDeployment(payload.new as deployments)
}
})
.subscribe()
return () => {
insertSub.unsubscribe()
updateSub.unsubscribe()
}
}, [
client,
project.id,
route?.id,
])
return deployment || initDeployment
}