Support custom client request, notification, and result types
This commit is contained in:
parent
9b4c949f65
commit
7cc7e81387
1 changed files with 102 additions and 4 deletions
71
src/client/index.test.ts
Normal file
71
src/client/index.test.ts
Normal file
|
|
@ -0,0 +1,71 @@
|
|||
import { Client } from "./index.js";
|
||||
import { z } from "zod";
|
||||
import { RequestSchema, NotificationSchema, ResultSchema } from "../types.js";
|
||||
|
||||
/*
|
||||
Test that custom request/notification/result schemas can be used with the Client class.
|
||||
*/
|
||||
const GetWeatherRequestSchema = RequestSchema.extend({
|
||||
method: z.literal("weather/get"),
|
||||
params: z.object({
|
||||
city: z.string(),
|
||||
}),
|
||||
});
|
||||
|
||||
const GetForecastRequestSchema = RequestSchema.extend({
|
||||
method: z.literal("weather/forecast"),
|
||||
params: z.object({
|
||||
city: z.string(),
|
||||
days: z.number(),
|
||||
}),
|
||||
});
|
||||
|
||||
const WeatherForecastNotificationSchema = NotificationSchema.extend({
|
||||
method: z.literal("weather/alert"),
|
||||
params: z.object({
|
||||
severity: z.enum(["warning", "watch"]),
|
||||
message: z.string(),
|
||||
}),
|
||||
});
|
||||
|
||||
const WeatherRequestSchema = GetWeatherRequestSchema.or(
|
||||
GetForecastRequestSchema,
|
||||
);
|
||||
const WeatherNotificationSchema = WeatherForecastNotificationSchema;
|
||||
const WeatherResultSchema = ResultSchema.extend({
|
||||
temperature: z.number(),
|
||||
conditions: z.string(),
|
||||
});
|
||||
|
||||
type WeatherRequest = z.infer<typeof WeatherRequestSchema>;
|
||||
type WeatherNotification = z.infer<typeof WeatherNotificationSchema>;
|
||||
type WeatherResult = z.infer<typeof WeatherResultSchema>;
|
||||
|
||||
// Create a typed Client for weather data
|
||||
const weatherClient = new Client<
|
||||
WeatherRequest,
|
||||
WeatherNotification,
|
||||
WeatherResult
|
||||
>({
|
||||
name: "WeatherClient",
|
||||
version: "1.0.0",
|
||||
});
|
||||
|
||||
// Typecheck that only valid weather requests/notifications/results are allowed
|
||||
weatherClient.request(
|
||||
{
|
||||
method: "weather/get",
|
||||
params: {
|
||||
city: "Seattle",
|
||||
},
|
||||
},
|
||||
WeatherResultSchema,
|
||||
);
|
||||
|
||||
weatherClient.notification({
|
||||
method: "weather/alert",
|
||||
params: {
|
||||
severity: "warning",
|
||||
message: "Storm approaching",
|
||||
},
|
||||
});
|
||||
Loading…
Reference in a new issue