Skip to content

workloads / main / Broadcast

Class: Broadcast<T, S> ​

Creates a Broadcast workloads

The constructore takes a session handler and a configuration object for channels. Each channel is mapped to a path and an optional authorization handler. The channel paths can include dynamic segments, like /users/[id], which are parsed and passed to the authorization logic.

Param ​

A function that resolves to a session object. This object is available within the authorization handlers. It receives an object with cookies as an argument.

Param ​

An object where keys are route strings and values are objects defining the channel and its authorization logic.

  • auth: An optional function to authorize "PUBLISH" or "SUBSCRIBE" operations. It receives the operation type, route parameters, and the session object.
  • channel: The channel instance for the route.

Example ​

ts
import { channel, Broadcast } from "@monolayer/sdk";

const broadcast = new Broadcast(
  async () => ({ userId: 1 }),
  {
    "/todos": {
      channel: channel<{ message: string }>(),
      auth: async (ctx) => {
        console.log("User trying to access todos:", ctx.session.userId);
        return true; // Allow access
      },
    },
    "/users/[id]": {
      channel: channel<{ salute: string }>(),
      auth: async (ctx) => {
        // Only allow users to access their own channel
        return ctx.session.userId === Number(ctx.params.id);
      },
    },
  }
);

export default broadcast;

Extends ​

Type Parameters ​

Type ParameterDescription

T extends Record<string, any>

A record mapping channel strings to their channel data types.

S

The type of the session object, returned by the session function.

Accessors ​

connectionStringEnvVar ​

Get Signature ​

ts
get connectionStringEnvVar(): "ML_BROADCAST_URL"
Returns ​

"ML_BROADCAST_URL"

Constructors ​

new Broadcast() ​

ts
new Broadcast<T, S>(initOpts): Broadcast<T, S>

Parameters ​

ParameterType

initOpts

object

initOpts.channels

{ [channel in string | number | symbol]: ValidateRoute<channel & string> extends never ? never : Object }

initOpts.session?

(opts) => Promise<S>

Returns ​

Broadcast<T, S>

Overrides ​

Workload.constructor

Methods ​

authFn() ​

ts
authFn(
   route, 
   operation, 
session): Promise<boolean>

Parameters ​

ParameterType

route

string

operation

"PUBLISH" | "SUBSCRIBE"

session

S

Returns ​

Promise<boolean>

Properties ​

PropertyModifierTypeDescription
_channelDataTypepublic{ [K in string | number | symbol]: T[K] }-
channelspublic{ [channel in string | number | symbol]: ValidateRoute<channel & string> extends never ? never : Object }-
idreadonlystringUnique ID
sessionpublic(opts: object) => Promise<S>-