|
| 1 | +import { Server } 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 Server 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 Server for weather data |
| 45 | +const weatherServer = new Server< |
| 46 | + WeatherRequest, |
| 47 | + WeatherNotification, |
| 48 | + WeatherResult |
| 49 | +>({ |
| 50 | + name: "WeatherServer", |
| 51 | + version: "1.0.0", |
| 52 | +}); |
| 53 | + |
| 54 | +// Typecheck that only valid weather requests/notifications/results are allowed |
| 55 | +weatherServer.setRequestHandler(GetWeatherRequestSchema, (request) => { |
| 56 | + return { |
| 57 | + temperature: 72, |
| 58 | + conditions: "sunny", |
| 59 | + }; |
| 60 | +}); |
| 61 | + |
| 62 | +weatherServer.setNotificationHandler( |
| 63 | + WeatherForecastNotificationSchema, |
| 64 | + (notification) => { |
| 65 | + console.log(`Weather alert: ${notification.params.message}`); |
| 66 | + }, |
| 67 | +); |
0 commit comments