| 219 | }[keyof TMessageCatalog]; |
| 220 | |
| 221 | export class ZodSocketMessageSender<TMessageCatalog extends ZodSocketMessageCatalogSchema> { |
| 222 | #schema: TMessageCatalog; |
| 223 | #socket: ZodSocket<any, TMessageCatalog>; |
| 224 | |
| 225 | constructor(options: ZodSocketMessageSenderOptions<TMessageCatalog>) { |
| 226 | this.#schema = options.schema; |
| 227 | this.#socket = options.socket; |
| 228 | } |
| 229 | |
| 230 | public send<K extends GetSocketMessagesWithoutCallback<TMessageCatalog>>( |
| 231 | type: K, |
| 232 | payload: z.input<GetSocketMessageSchema<TMessageCatalog, K>> |
| 233 | ): void { |
| 234 | const schema = this.#schema[type]["message"]; |
| 235 | |
| 236 | if (!schema) { |
| 237 | throw new Error(`Unknown message type: ${type as string}`); |
| 238 | } |
| 239 | |
| 240 | const parsedPayload = schema.safeParse(payload); |
| 241 | |
| 242 | if (!parsedPayload.success) { |
| 243 | throw new Error(`Failed to parse message payload: ${JSON.stringify(parsedPayload.error)}`); |
| 244 | } |
| 245 | |
| 246 | // @ts-expect-error |
| 247 | this.#socket.emit(type, { payload, version: "v1" }); |
| 248 | |
| 249 | return; |
| 250 | } |
| 251 | |
| 252 | public async sendWithAck<K extends GetSocketMessagesWithCallback<TMessageCatalog>>( |
| 253 | type: K, |
| 254 | payload: z.input<GetSocketMessageSchema<TMessageCatalog, K>> |
| 255 | ): Promise<z.infer<GetSocketCallbackSchema<TMessageCatalog, K>>> { |
| 256 | const schema = this.#schema[type]["message"]; |
| 257 | |
| 258 | if (!schema) { |
| 259 | throw new Error(`Unknown message type: ${type as string}`); |
| 260 | } |
| 261 | |
| 262 | const parsedPayload = schema.safeParse(payload); |
| 263 | |
| 264 | if (!parsedPayload.success) { |
| 265 | throw new Error(`Failed to parse message payload: ${JSON.stringify(parsedPayload.error)}`); |
| 266 | } |
| 267 | |
| 268 | // @ts-expect-error |
| 269 | const callbackResult = await this.#socket.emitWithAck(type, { payload, version: "v1" }); |
| 270 | |
| 271 | return callbackResult; |
| 272 | } |
| 273 | } |
| 274 | |
| 275 | export type ZodSocket< |
| 276 | TListenEvents extends ZodSocketMessageCatalogSchema, |
nothing calls this directly
no outgoing calls
no test coverage detected
searching dependent graphs…