UNPKG

bun-ws-router

Version:

A simple and efficient WebSocket router for Bun with Zod/Valibot message validation.

36 lines 1.32 kB
/* SPDX-FileCopyrightText: 2025-present Kriasoft */ /* SPDX-License-Identifier: MIT */ /** * Generic publish function that works with any validator adapter. */ export function publishWithValidator(validator, server, topic, schema, messageType, // eslint-disable-next-line @typescript-eslint/no-explicit-any payload, // eslint-disable-next-line @typescript-eslint/no-explicit-any meta = {}) { try { // Create the message object with the required structure const message = { type: messageType, meta: { timestamp: Date.now(), ...meta, }, ...(payload !== undefined && { payload }), }; // Validate the constructed message against the schema const validationResult = validator.safeParse(schema, message); if (!validationResult.success) { console.error(`[ws] Failed to publish message of type "${messageType}": Validation error`, validationResult.error); return false; } // Publish the validated message server.publish(topic, JSON.stringify(validationResult.data)); return true; } catch (error) { console.error(`[ws] Error publishing message:`, error); return false; } } //# sourceMappingURL=publish.js.map