From af8465b7fdc3f868da5c77125c07f53289bf1c45 Mon Sep 17 00:00:00 2001 From: Anders Kaseorg Date: Mon, 23 Oct 2023 12:46:30 -0700 Subject: [PATCH] billing: Replace unchecked keyof casts with Zod schemas. Signed-off-by: Anders Kaseorg --- web/src/billing/helpers.ts | 23 +++++++++++------------ web/src/billing/upgrade.ts | 8 ++++---- 2 files changed, 15 insertions(+), 16 deletions(-) diff --git a/web/src/billing/helpers.ts b/web/src/billing/helpers.ts index 70b114b88a..7bfacc8c0a 100644 --- a/web/src/billing/helpers.ts +++ b/web/src/billing/helpers.ts @@ -7,19 +7,18 @@ import {page_params} from "./page_params"; type FormDataObject = Record; -export type Prices = { - monthly: number; - annual: number; -}; +export const schedule_schema = z.enum(["monthly", "annual"]); +export type Prices = Record, number>; -export type DiscountDetails = { - opensource: string; - research: string; - nonprofit: string; - event: string; - education: string; - education_nonprofit: string; -}; +export const organization_type_schema = z.enum([ + "opensource", + "research", + "nonprofit", + "event", + "education", + "education_nonprofit", +]); +export type DiscountDetails = Record, string>; export const stripe_session_url_schema = z.object({ stripe_session_url: z.string(), diff --git a/web/src/billing/upgrade.ts b/web/src/billing/upgrade.ts index f14e6f4722..8e7ab79700 100644 --- a/web/src/billing/upgrade.ts +++ b/web/src/billing/upgrade.ts @@ -1,7 +1,7 @@ import $ from "jquery"; import * as helpers from "./helpers"; -import type {DiscountDetails, Prices} from "./helpers"; +import type {Prices} from "./helpers"; import {page_params} from "./page_params"; export const initialize = (): void => { @@ -42,14 +42,14 @@ export const initialize = (): void => { }); $("input[type=radio][name=schedule]").on("change", function (this: HTMLInputElement) { - helpers.update_charged_amount(prices, this.value as keyof Prices); + helpers.update_charged_amount(prices, helpers.schedule_schema.parse(this.value)); }); $("select[name=organization-type]").on("change", (e) => { const string_value = $((e.currentTarget as HTMLSelectElement).selectedOptions).attr( "data-string-value", ); - helpers.update_discount_details(string_value as keyof DiscountDetails); + helpers.update_discount_details(helpers.organization_type_schema.parse(string_value)); }); $("#autopay_annual_price").text(helpers.format_money(prices.annual)); @@ -63,7 +63,7 @@ export const initialize = (): void => { ); helpers.update_charged_amount( prices, - $("input[type=radio][name=schedule]:checked").val() as keyof Prices, + helpers.schedule_schema.parse($("input[type=radio][name=schedule]:checked").val()), ); };