| 315 | } |
| 316 | |
| 317 | export class ZodSocketConnection< |
| 318 | TClientMessages extends ZodSocketMessageCatalogSchema, |
| 319 | TServerMessages extends ZodSocketMessageCatalogSchema, |
| 320 | > { |
| 321 | #sender: ZodSocketMessageSender<TClientMessages>; |
| 322 | socket: ZodSocket<TServerMessages, TClientMessages>; |
| 323 | |
| 324 | #handler: ZodSocketMessageHandler<TServerMessages>; |
| 325 | #logger: StructuredLogger; |
| 326 | |
| 327 | constructor(opts: ZodSocketConnectionOptions<TClientMessages, TServerMessages>) { |
| 328 | const uri = `${opts.secure ? "wss" : "ws"}://${opts.host}:${ |
| 329 | opts.port ?? (opts.secure ? "443" : "80") |
| 330 | }/${opts.namespace}`; |
| 331 | |
| 332 | const logger = new SimpleStructuredLogger(opts.namespace, LogLevel.info); |
| 333 | logger.log("new zod socket", { uri }); |
| 334 | |
| 335 | this.socket = io(uri, { |
| 336 | transports: ["websocket"], |
| 337 | auth: { |
| 338 | token: opts.authToken, |
| 339 | }, |
| 340 | extraHeaders: opts.extraHeaders, |
| 341 | reconnectionDelay: 500, |
| 342 | reconnectionDelayMax: 1000, |
| 343 | }); |
| 344 | |
| 345 | this.#logger = logger.child({ |
| 346 | socketId: this.socket.id, |
| 347 | }); |
| 348 | |
| 349 | this.#handler = new ZodSocketMessageHandler({ |
| 350 | schema: opts.serverMessages, |
| 351 | handlers: opts.handlers, |
| 352 | }); |
| 353 | this.#handler.registerHandlers(this.socket, this.#logger); |
| 354 | |
| 355 | this.#sender = new ZodSocketMessageSender({ |
| 356 | schema: opts.clientMessages, |
| 357 | socket: this.socket, |
| 358 | }); |
| 359 | |
| 360 | this.socket.on("connect_error", async (error) => { |
| 361 | this.#logger.error(`connect_error: ${error}`); |
| 362 | |
| 363 | if (opts.onError) { |
| 364 | await opts.onError(this.socket, error, this.#logger); |
| 365 | } |
| 366 | }); |
| 367 | |
| 368 | this.socket.on("connect", async () => { |
| 369 | this.#logger.info("connect"); |
| 370 | |
| 371 | if (opts.onConnection) { |
| 372 | await opts.onConnection(this.socket, this.#handler, this.#sender, this.#logger); |
| 373 | } |
| 374 | }); |
nothing calls this directly
no outgoing calls
no test coverage detected
searching dependent graphs…