Added realtime subcription to calendar page

This commit is contained in:
Alexis
2024-08-24 22:34:51 +02:00
parent 245b46661a
commit 1985ffdbe9
2 changed files with 61 additions and 1 deletions

View File

@@ -1,13 +1,16 @@
<script lang="ts" setup>
import type { RealtimeChannel } from '@supabase/supabase-js'
import { PhPlus } from '@phosphor-icons/vue';
import type { World } from '~/models/World';
import type { Calendar } from '~/models/CalendarConfig';
const supabase = useSupabaseClient()
const route = useRoute()
const id = route.params.id
const { data: res, pending } = await useFetch('/api/worlds/query', { query: { id, full: true } })
const world = res.value?.data as World
const world = ref<World>(res.value?.data as World)
useHead({
title: 'Profil'
@@ -30,6 +33,60 @@ const alertModalOpened = ref<boolean>(false)
function handleDialogClose() {
alertModalOpened.value = false
}
/**
* === Calendar subscriptions ===
*/
/** Active calendar channel */
let calendarChannel: RealtimeChannel
/** Handles calendar insertion realtime events */
function handleInsertedCalendar(newCalendar: Calendar) {
try {
world.value.calendars?.push(newCalendar)
} catch (err) {
console.log(err)
}
}
/** Handles calendar deletion realtime events */
function handleDeletedCalendar(id: number) {
try {
world.value.calendars?.splice(world.value.calendars.findIndex(c => c.id === id))
} catch (err) {
console.log(err)
}
}
onMounted(() => {
calendarChannel = supabase.channel('custom-insert-channel')
.on(
'postgres_changes',
{ event: '*', schema: 'public', table: 'calendars' },
(payload) => {
switch (payload.eventType) {
case 'INSERT':
handleInsertedCalendar(payload.new as Calendar)
break
case 'DELETE':
handleDeletedCalendar(payload.old.id)
break
default:
console.log('Unknown event has been triggered. This should not happen unless Supabase added one somehow.')
break
}
}
)
.subscribe()
})
onUnmounted(() => {
// Unsubscribe from realtime
supabase.removeChannel(calendarChannel)
})
</script>
<template>

View File

@@ -160,6 +160,9 @@ alter table public.calendar_events enable row level security;
alter table public.calendar_event_categories enable row level security;
alter table public.calendar_event_categories_links enable row level security;
-- Add realtime
alter publication supabase_realtime add table calendars;
-- User policies
create policy "Allow logged-in read access" on public.users for select using ( auth.role() = 'authenticated' );
create policy "Allow individual insert access" on public.users for insert with check ( auth.uid() = id );