Skip to content

Commit

Permalink
widgets: Make Zod schema for widget extra data stricter and extendable.
Browse files Browse the repository at this point in the history
The schema now ensures extra data is validated according to the widget
type. This also makes it easier to modify the extra data for any widget
or add new widget types in the future.
  • Loading branch information
N-Shar-ma authored and timabbott committed Apr 14, 2024
1 parent 5990835 commit 8c000f3
Showing 1 changed file with 26 additions and 23 deletions.
49 changes: 26 additions & 23 deletions web/src/submessage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,32 +7,35 @@ import type {Message} from "./message_store";
import type {Submessage} from "./types";
import * as widgetize from "./widgetize";

export const zform_widget_extra_data_schema = z.object({
choices: z.array(
z.object({
type: z.string(),
long_name: z.string(),
reply: z.string(),
short_name: z.string(),
}),
),
heading: z.string(),
type: z.literal("choices"),
});

const poll_widget_extra_data_schema = z.object({
question: z.string().optional(),
options: z.array(z.string()).optional(),
});
export const zform_widget_extra_data_schema = z
.object({
choices: z.array(
z.object({
type: z.string(),
long_name: z.string(),
reply: z.string(),
short_name: z.string(),
}),
),
heading: z.string(),
type: z.literal("choices"),
})
.nullable();

const poll_widget_extra_data_schema = z
.object({
question: z.string().optional(),
options: z.array(z.string()).optional(),
})
.nullable();

const widget_data_event_schema = z.object({
sender_id: z.number(),
data: z.object({
widget_type: z.string().optional(),
extra_data: z
.union([zform_widget_extra_data_schema, poll_widget_extra_data_schema])
.nullable(),
}),
data: z.discriminatedUnion("widget_type", [
z.object({widget_type: z.literal("poll"), extra_data: poll_widget_extra_data_schema}),
z.object({widget_type: z.literal("zform"), extra_data: zform_widget_extra_data_schema}),
z.object({widget_type: z.literal("todo"), extra_data: z.null()}),
]),
});

const inbound_data_event_schema = z.object({
Expand Down

0 comments on commit 8c000f3

Please sign in to comment.