Skip to content

Instantly share code, notes, and snippets.

@alexvdvalk
Created June 15, 2023 14:04
Show Gist options
  • Save alexvdvalk/e2f2ac075b8d95137457bc0986ff7583 to your computer and use it in GitHub Desktop.
Save alexvdvalk/e2f2ac075b8d95137457bc0986ff7583 to your computer and use it in GitHub Desktop.
Sveltekit Directus Websockets Demo
<script lang="ts">
import { onMount } from 'svelte';
const url = 'ws://localhost:8055/websocket';
const access_token = 'your key';
const collection = 'posts';
onMount(() => {
const connection = new WebSocket(url);
connection.addEventListener('open', function () {
console.log({ event: 'onopen' });
connection.send(
JSON.stringify({
type: 'auth',
access_token
})
);
});
connection.addEventListener('message', function (message) {
// Message is type of "MessageEvent" so cannot parse to JSON
const data = JSON.parse(message.data);
console.log({ event: 'onmessage', message: data });
//{type: 'auth', status: 'ok'}
if (data.type === 'auth' && data.status === 'ok') {
subscribe();
}
});
connection.addEventListener('close', function () {
console.log({ event: 'onclose' });
});
connection.addEventListener('error', function (error) {
console.log({ event: 'onerror', error });
});
function subscribe() {
connection.readyState;
connection.send(
JSON.stringify({
type: 'subscribe',
collection: collection,
query: { fields: ['*'] }
})
);
}
//
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment