Emitting
Once you have successfully built a registration flow for your users (see the Registering guides if you have not), you are able to emit to those registered users anywhere in your application (yes, including within background jobs!).
PsychicAppWebsocketsWs.emit() boots a PsychicAppWebsockets instance on its first call. Each Node process has its own module cache — the websocket app instance is not shared across processes. If any process skips PsychicAppWebsockets.init() (e.g. via a service-role guard that is too narrow), the call throws:
must call `cachePsychicAppWebsockets` before loading cached psychic application websockets
By default the generated initializer runs in all processes. See Config for details and the optional role guard.
To establish a new Ws instance, we need to provide it with a set of routes that the application allows, like so:
const wsRoutes = ['/users/ping', 'users/alert', 'users/info'] as const
ws = new Ws(wsRoutes)
For your convenience, we recommend that you set up a simple helper function in your application to wrap this, as well as to establish a singleton, so as to prevent multiple instances from needing to establish independent connections:
// app/helpers/ws.ts
import { Ws } from '@rvoh/psychic-websockets'
export const WS_ROUTES = ['/ops/connection-success'] as const
const ws = new Ws(WS_ROUTES)
export default ws
Once this has been established, you can now emit to your users with any of the provided routes:
await ws.emit(user, '/users/ping', { hello: 'world' })