Files
sync-server-example/source/ws/types.ts
T
2026-10-22 15:19:06 +00:00

41 lines
1.4 KiB
TypeScript

import { z } from 'zod';
/** A normal, correlated reply to a WebSocket request. */
export const WsSuccessResponseSchema = z.object({
id: z.string().optional(),
type: z.literal('response'),
statusCode: z.number(),
body: z.unknown(),
});
export type WsSuccessResponse = z.infer<typeof WsSuccessResponseSchema>;
/** A public error returned by the server for one request. */
export const WsErrorResponseSchema = z.object({
id: z.string().optional(),
type: z.literal('error'),
statusCode: z.number(),
error: z.string(),
details: z.unknown().optional(),
});
export type WsErrorResponse = z.infer<typeof WsErrorResponseSchema>;
export const WsResponseSchema = z.discriminatedUnion('type', [ WsSuccessResponseSchema, WsErrorResponseSchema ]);
export type WsResponse = z.infer<typeof WsResponseSchema>;
/**
* A server-pushed application event.
*
* Sync resource changes currently use the type `instance-changed`, but the
* client deliberately leaves `type` open so this demo does not need updating
* whenever the server adds another event.
*/
export const WsEventSchema = z.object({
id: z.string().optional(),
type: z.string(),
data: z.unknown(),
});
export type WsEvent = z.infer<typeof WsEventSchema>;
export const WsMessageSchema = z.union([ WsResponseSchema, WsEventSchema ]);
export type WsMessage = z.infer<typeof WsMessageSchema>;