42 lines
1018 B
TypeScript
42 lines
1018 B
TypeScript
import type { QuestionType } from "@/db/schema/form";
|
|
|
|
export type FormAnswerValue = string | string[];
|
|
|
|
export function decodeCheckboxAnswer(value: FormAnswerValue | undefined): string[] {
|
|
if (Array.isArray(value)) {
|
|
return value.filter((item): item is string => typeof item === "string");
|
|
}
|
|
|
|
if (!value) {
|
|
return [];
|
|
}
|
|
|
|
try {
|
|
const parsed: unknown = JSON.parse(value);
|
|
if (Array.isArray(parsed) && parsed.every((item) => typeof item === "string")) {
|
|
return parsed;
|
|
}
|
|
} catch {
|
|
// Older checkbox answers were stored as comma-separated text.
|
|
}
|
|
|
|
return value.split(", ").filter(Boolean);
|
|
}
|
|
|
|
export function encodeAnswerValue(value: FormAnswerValue): string {
|
|
return Array.isArray(value) ? JSON.stringify(value) : value;
|
|
}
|
|
|
|
export function formatStoredAnswer(
|
|
value: string | undefined,
|
|
questionType: QuestionType | string
|
|
): string {
|
|
if (!value) {
|
|
return "";
|
|
}
|
|
|
|
return questionType === "checkbox"
|
|
? decodeCheckboxAnswer(value).join(", ")
|
|
: value;
|
|
}
|