Skip to content

Instantly share code, notes, and snippets.

@maietta
Last active November 28, 2024 22:03
Show Gist options
  • Select an option

  • Save maietta/665cdb8951b8ab87ba11bbdd087f375a to your computer and use it in GitHub Desktop.

Select an option

Save maietta/665cdb8951b8ab87ba11bbdd087f375a to your computer and use it in GitHub Desktop.
Front-end reacting to changes in Pocketbase, but using Pocketbase on the backend, not the front-end.
<script lang="ts">
import '../app.css';
let { children }: { children: any } = $props();
import { source } from 'sveltekit-sse';
const value = source('/api/config').select('message'); // Use $value to access the store
</script>
<p>Fiddle with field change in Pocketbase to see this update in realtime</p>
{JSON.stringify($value)}
{@render children()}
// api/config/+server.ts
import { produce } from 'sveltekit-sse';
import pb from '$lib/pocketbase';
// The POST function sets up the SSE and emits updates when `siteType` changes.
export function POST({ locals }: any) {
return produce(async function start({ emit }) {
let previousValue = locals.config.siteType; // Set in hooks.., definition in apps.d.ts
// Subscribe to the 'websites' collection for changes
pb.collection('websites').subscribe('*', async (event) => {
// Check if the event is of type "update" and if it includes a `siteType` field
if (event.action === 'update' && event.record.siteType) {
const newValue = event.record.siteType;
// Update the locals.config.siteType if it has changed
if (newValue !== previousValue) {
const { error } = emit("message", newValue);
if (error) {
console.error('Error emitting message:', error);
}
previousValue = newValue; // Update previous value after emitting
}
}
});
});
}
import PocketBase from 'pocketbase';
import { env } from '$env/dynamic/private';
import eventsource from 'eventsource';
// global.EventSource = eventsource as unknown as typeof EventSource;
globalThis.EventSource = eventsource as unknown as typeof EventSource;
const pb = new PocketBase(env.POCKETBASE_URL);
pb.autoCancellation(false);
export default pb;
@maietta
Copy link
Author

maietta commented Nov 28, 2024

Dependencies:

eventsource
sveltekit-sse

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment