Start typing to search...
API Reference
Deprecated
@withkoji/dispatch
Search

@withkoji/dispatch (deprecated)

Warning

This package is deprecated and is included only for backwards compatibility. For new templates, use withkoji-koji-core.html.

The @withkoji/dispatch package enables you to implement real-time functionality in your Koji template. For example, chats, multi-player games, and polls.

You can use dispatch on the frontend to enable real-time updates and communication between connected clients. You can also use it transactionally on the backend to send secure messages to specific clients that have been identified with a short-lived token.

Install

Install the package in your Koji project.

Note
You must also install the withkoji-vcc-package.html package.
npm i --save @withkoji/dispatch

Dispatch

new Dispatch(project)

Instantiates Dispatch.

Parameters

  • projectObject, dispatch configuration for your Koji project. Contains the following properties:

    • projectIdString, unique identifier for your Koji project. You can use the withkoji-vcc-package.html package to obtain this value programmatically.

    • options – (Optional on frontend) Object, configuration options for the dispatch instance. Contains the following properties:

      • shardName – (Optional) String, name of the specific shard to use. If this key is not present, the user will be placed into a shard automatically.

      • maxConnectionsPerShard– (Optional) Number, total users to allow on a shard before it is "full." When a shard is full, new users are added to a new shard unless a different shard is explicitly set.

      • projectToken – (Backend only) String, secret key for the Koji.

      • authorization – (Backend only, Optional) String, temporary token that identifies the client, so the server and other connected clients can send it secure messages. If the token is not included, you can use identify to identify the client after it is connected.

Example

import Dispatch from '@withkoji/dispatch';

// Frontend
const dispatch = new Dispatch({
  projectId: instantRemixing.get(['metadata', 'projectId']),
});

// Backend
const dispatch = new Dispatch({
  projectId: res.locals.KOJI_PROJECT_ID || process.env.KOJI_PROJECT_ID,
  options: {
    projectToken: res.locals.KOJI_PROJECT_TOKEN || process.env.KOJI_PROJECT_TOKEN,
  },
});

Dispatch properties

.authToken

String, temporary token that identifies the connected client, so the server and other connected clients can send it secure messages. To get a token, use getToken in the @withkoji/auth package.

.clientId

String, ID of the currently connected client.

.connectedClients

Object, contains IDs of currently connected clients as keys and an object of their user data.

Example

{
	"0dc15e36-81b4-442b-be4d-bf590ee73c2a": {
		username: "test1",
		lastPing: 1600218622595
	},
	"1fe2eb80-57e3-435f-9314-faa74853c34a": {
		username: "test2",
		lastPing: 1600218623097
	}
}

.latency

Number, the latency of the last message in milliseconds.

.shardName

String, name of the shard the client is currently connected to.

.userInfo

Object, the user information of the currently connected client. This can be modified using .setUserInfo.

Dispatch methods

.connect()

(Async) Connects the dispatch client to an open shard.

Example

dispatch.connect();

.disconnect()

(Async) Disconnects the dispatch client from the active connection.

Example

dispatch.disconnect();

.emitEvent(eventName, payload, recipients)

Emits the named event to the specified recipients or all clients.

Parameters

  • eventNameString, name of the event.

  • payloadAny, data to send with event.

  • recipients – (Optional) Array of Strings, list of clients to receive the event. If this parameter is not included, the event is sent to all clients on the current shard.

Example

dispatch.emitEvent('myEvent', myDataPayload);

.identify(authToken)

Identifies a connected client, which enables the server and other connected clients to send it secure messages.

Parameters

  • authTokenString, temporary token for the connected client. To get a token, use getToken in the @withkoji/auth package.

Example

token = await auth.getToken(
  ['username', 'push_notifications'],
);
dispatch.identify(token);

.info()

Gets information about the shard the client is currently connected to.

Returns

(Async) ShardInfo, Object describing the shard the client is currently connected to with shard name and number of connected clients.

Example

dispatch.info.then((info) => {
    currentInfo = info;
});

.on(eventName, handler)

Sets a listener for a specific event, and runs the handler when the event is dispatched over the shard.

Parameters

  • eventNameString, name of the event to subscribe to.

  • handlerFunction, the handler to run when the event is fired. Receives the following property as input:

    • payloadAny, the data payload sent from the fired event.

Example

dispatch.on('myEvent', myHandlerFunction);

// or with a custom payload
dispatch.on('myOtherEvent', (payload) => {
	// payload sent from the emitted event available here
});

.removeEventListener(eventName)

Removes listeners from the specified event.

Parameters

  • eventNameString, name of the event to unsubscribe from.

Example

dispatch.removeEventListener('myEvent');

.setUserInfo(userInfo)

Sets the current user’s information (see .userInfo) and broadcasts the update in the currently connected shard.

Parameters

  • userInfoAny, the data for user information to set.

Example

dispatch.setUserInfo({username:"myUsername"});

Dispatch constants

DISPATCH_EVENT

Constant holding special event keys for Koji Dispatch. To subscribe to these events see on.

  1. DISPATCH_EVENT.CONNECTED – Fired when the current client has successfully connected to a shard. Passes the following properties in its payload object:

    1. clientID - String, Unique ID of the user on the shard that’s been connected to

    2. shardName - String, Name of the shard that’s been connected to

  2. DISPATCH_EVENT.CONNECTED_CLIENTS_CHANGED - Fired when the list of clients currently connected to the shard changes. Passes the following property in its payload object:

    1. connectedClients - Object, Mapping of connected client’s IDs and their respective userInfo.

Example

import Dispatch, { DISPATCH_EVENT } from '@withkoji/dispatch';

const dispatch = new Dispatch({
  projectId: instantRemixing.get(['metadata', 'projectId'])
});

dispatch.connect();

dispatch.on(DISPATCH_EVENT.CONNECTED, ({ clientId, shardName }) => {
	// client has connected to shard
});

dispatch.on(DISPATCH_EVENT.CONNECTED_CLIENTS_CHANGED, ({ connectedClients }) => {
	// connected clients has changed
});

Utils

Koji dispatch includes utility functions to help you build realtime multiplayer games and applications.

import { Utils } from '@withkoji/dispatch';

.profanity(string)

Checks whether a string contains profanity. This method can be useful for checking usernames or chat content.

Parameters

  • stringString, text to check.

Returns

Boolean, indicates whether the specified string contains profanity.

Example

Utils.profanity('check this string');

.filterProfanity(string)

Replaces profanity in a string with asterisks.

Parameters

  • stringString, text to sanitize.

Returns

String, text with profanities replaced with asterisks.

Example

Utils.filterProfanity('sanitize this string');