decentralised sync engine
0
fork

Configure Feed

Select the types of activity you want to include in your feed.

refactor: validation

serenity 4bedde9c 848b4af9

+46 -12
+1 -1
src/lib/utils/registration.ts
··· 3 3 import { prismCommitSchema } from "@/lib/types/prism"; 4 4 import type { RouteHandler, WsRouteHandler } from "@/lib/types/routes"; 5 5 import { newErrorResponse } from "@/lib/utils/http/responses"; 6 - import { rawDataToString } from "@/lib/utils/ws"; 6 + import { rawDataToString } from "@/lib/utils/ws/validate"; 7 7 import type { RawData } from "ws"; 8 8 import type WebSocket from "ws"; 9 9
-11
src/lib/utils/ws/index.ts
··· 1 - import type { RawData } from "ws"; 2 - 3 - export const rawDataToString = (data: RawData): string => { 4 - if (Buffer.isBuffer(data)) { 5 - return data.toString("utf-8"); 6 - } 7 - if (Array.isArray(data)) { 8 - return Buffer.concat(data).toString("utf-8"); 9 - } 10 - return new TextDecoder().decode(data); 11 - };
+45
src/lib/utils/ws/validate.ts
··· 1 + import type { WebsocketMessage } from "@/lib/types/messages"; 2 + import { websocketMessageSchema } from "@/lib/types/messages"; 3 + import type { Result } from "@/lib/utils/result"; 4 + import { z } from "zod"; 5 + import type { RawData } from "ws"; 6 + 7 + export const rawDataToString = (data: RawData): string => { 8 + if (Buffer.isBuffer(data)) { 9 + return data.toString("utf-8"); 10 + } 11 + if (Array.isArray(data)) { 12 + return Buffer.concat(data).toString("utf-8"); 13 + } 14 + return new TextDecoder().decode(data); 15 + }; 16 + 17 + export const validateWsMessageString = ( 18 + data: unknown, 19 + ): Result<string, unknown> => { 20 + const { success, error, data: message } = z.string().safeParse(data); 21 + if (!success) { 22 + console.error("Error decoding websocket message"); 23 + console.error(error); 24 + return { ok: false, error: z.treeifyError(error) }; 25 + } 26 + return { ok: true, data: message }; 27 + }; 28 + 29 + export const validateWsMessageType = ( 30 + data: unknown, 31 + ): Result<WebsocketMessage, unknown> => { 32 + const { 33 + success: wsMessageSuccess, 34 + error: wsMessageError, 35 + data: wsMessage, 36 + } = websocketMessageSchema.safeParse(data); 37 + if (!wsMessageSuccess) { 38 + console.error( 39 + "Error parsing websocket message. The data might be the wrong shape.", 40 + ); 41 + console.error(wsMessageError); 42 + return { ok: false, error: z.treeifyError(wsMessageError) }; 43 + } 44 + return { ok: true, data: wsMessage }; 45 + };