Client for the django-instant websockets backend
npm install djangoinstant
// or
yarn add djangoinstant
Initialize the client
import { useInstant } from "djangoinstant";
const instant = useInstant();
await instant.init(
"http://localhost:8000", // backend url
"ws://localhost:8427", // websockets url
true // verbosity
)
init
structure:
(backendUrl: string, websocketsUrl: string, verbose?: boolean) => Promise<void>
Login with Django and get credentials for websockets:
await instant.login("some_username", "some_password");
If the user is already logged in just get the websockets connection credentials:
await instant.get_token();
Define a handler function and use it for all incoming messages:
import { Message } from "djangoinstant";
function onMessage(msg: Message): void {
switch (msg.channelName) {
case "public":
// process msg
break;
case "$users":
// process msg
break;
case "$group1":
// process msg
break;
default:
throw new Error(`Unknown channel ${msg.channelName}`)
}
}
instant.onMessage(onMessage);
Message structure:
class Message {
channelName: string;
msg: string;
data: Record<string, any> | Array<any>;
eventClass: string;
site: string;
bucket: string | null;
date: Date;
}
await instant.connect();
console.log("Websockets connected");
By default the connect
function will subscribe to all the authorized channels
for the user provided by the backend. To avoid this use await instant.connect(false)
. To
subscribe later to all channels:
instant.subscribe();
Note: a classic centrifuge-js client is
accessible with instant.getClient()
An example with a backend and a frontend is available