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