WebSockets
Llana ships with WebSockets so you can keep your frontend applications fully synchronized with your database.
Socket Connection
WebSockets use the same Hosts and Authentication settings as the main API endpoints. If you have user authentication setup then the WebSockets expect a a JWT token to be passed either as as a Bearer token or via the Auth > Token
value:
import { io } from "socket.io-client";
import { $llanaInstanceUrl, $llanaAccessToken } from "@/plugins/llana"
export const socket = io($llanaInstanceUrl, {
extraHeaders: {
Authorization: 'Bearer ' + $llanaAccessToken()
'x-llana-table': table,
},
auth: {
token: $llanaAccessToken()
}
});
It is important to pass your table
in the extraHeaders > x-llana-table
value, as we will use this to check permissions during the socket creation process.
Subscribing
You can subscribe to specific table updates, you will receive payloads as follows:
{
type: 'INSERT' | 'UPDATE' | 'DELETE'
[table_primary_key]: string | number
}
Here is an example subscription to the users_notifications
table via a Pinia Store:
export const useNotificationsStore = defineStore('notificationStore', {
state: () => <ListResponse<Notification>>defaultList(),
actions: {
bindEvents() {
try{
socket.on(users_notifications, (data: SocketData) => {
switch (data.type) {
case 'INSERT':
case 'UPDATE':
this.getNotification(data.id)
break
case 'DELETE':
this.deleteNotification(data.id)
break
}
});
}catch(e: any){
console.error(e)
socket.off(table)
}
},
}
})
If you are using our frontend plugins like Nuxt, we handle the WebSocket integration automatically.
Optional Configuration
The following .env
values can be used:
Variable | Details |
---|---|
CACHE_WS_IDENTITY_DATA_TTL | The TTL for caching websocket identities, defaults to 2 days |