djangoinstant
v0.5.0
Published
Client for the django-instant websockets backend
Downloads
28
Readme
Django Instant client
Client for the django-instant websockets backend
npm install djangoinstant
// or
yarn add djangoinstant
Usage
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>
Get a websockets connection authorization
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 handlers for messages
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;
}
Connect to the websockets server
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()
Example
An example with a backend and a frontend is available