|
| 1 | +import { Client } from "./index.js"; |
| 2 | +import { z } from "zod"; |
| 3 | +import { RequestSchema, NotificationSchema, ResultSchema } from "../types.js"; |
| 4 | + |
| 5 | +/* |
| 6 | +Test that custom request/notification/result schemas can be used with the Client class. |
| 7 | +*/ |
| 8 | +const GetWeatherRequestSchema = RequestSchema.extend({ |
| 9 | + method: z.literal("weather/get"), |
| 10 | + params: z.object({ |
| 11 | + city: z.string(), |
| 12 | + }), |
| 13 | +}); |
| 14 | + |
| 15 | +const GetForecastRequestSchema = RequestSchema.extend({ |
| 16 | + method: z.literal("weather/forecast"), |
| 17 | + params: z.object({ |
| 18 | + city: z.string(), |
| 19 | + days: z.number(), |
| 20 | + }), |
| 21 | +}); |
| 22 | + |
| 23 | +const WeatherForecastNotificationSchema = NotificationSchema.extend({ |
| 24 | + method: z.literal("weather/alert"), |
| 25 | + params: z.object({ |
| 26 | + severity: z.enum(["warning", "watch"]), |
| 27 | + message: z.string(), |
| 28 | + }), |
| 29 | +}); |
| 30 | + |
| 31 | +const WeatherRequestSchema = GetWeatherRequestSchema.or( |
| 32 | + GetForecastRequestSchema, |
| 33 | +); |
| 34 | +const WeatherNotificationSchema = WeatherForecastNotificationSchema; |
| 35 | +const WeatherResultSchema = ResultSchema.extend({ |
| 36 | + temperature: z.number(), |
| 37 | + conditions: z.string(), |
| 38 | +}); |
| 39 | + |
| 40 | +type WeatherRequest = z.infer<typeof WeatherRequestSchema>; |
| 41 | +type WeatherNotification = z.infer<typeof WeatherNotificationSchema>; |
| 42 | +type WeatherResult = z.infer<typeof WeatherResultSchema>; |
| 43 | + |
| 44 | +// Create a typed Client for weather data |
| 45 | +const weatherClient = new Client< |
| 46 | + WeatherRequest, |
| 47 | + WeatherNotification, |
| 48 | + WeatherResult |
| 49 | +>({ |
| 50 | + name: "WeatherClient", |
| 51 | + version: "1.0.0", |
| 52 | +}); |
| 53 | + |
| 54 | +// Typecheck that only valid weather requests/notifications/results are allowed |
| 55 | +weatherClient.request( |
| 56 | + { |
| 57 | + method: "weather/get", |
| 58 | + params: { |
| 59 | + city: "Seattle", |
| 60 | + }, |
| 61 | + }, |
| 62 | + WeatherResultSchema, |
| 63 | +); |
| 64 | + |
| 65 | +weatherClient.notification({ |
| 66 | + method: "weather/alert", |
| 67 | + params: { |
| 68 | + severity: "warning", |
| 69 | + message: "Storm approaching", |
| 70 | + }, |
| 71 | +}); |
0 commit comments