Files
khata-ui/react-openapi/utils/options.ts
2026-06-13 21:37:17 +05:30

46 lines
1.8 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { ResourceField, SelectOption } from "../types/config";
export function resolveTemplate(template: string, item: any): string {
if (/\{(\w+)\}/.test(template)) {
return template.replace(/\{(\w+)\}/g, (_, field: string) => String(item[field] ?? ''));
}
return String(item[template] ?? '');
}
export function getFieldOptions(field: ResourceField, relationData?: any[]): SelectOption[] {
// console.log('getFieldOptions called for field', field.label, 'type', field.type, 'enumOption', field.enumOption);
if (field.type === 'enum') {
return (field.options ?? []).map(opt => ({
key: opt,
value: field.enumLabels?.[opt] ?? opt,
}));
}
if (field.relation) {
const data = Array.isArray(relationData) ? relationData : [];
// console.log('Getting options for relation', field.relation, 'data count:', data.length);
if (data.length === 0) {
throw new Error(`Relation data for "${field.relation}" is missing or empty cannot build options for field "${field.label}"`);
}
const enumOption = field.enumOption;
if (!enumOption) {
throw new Error(
`Missing enumOption for relation "${field.relation}" on field "${field}". ` +
`Define referenceOptions.enumOption in the configuration for resource "${field.relation}".`
);
}
const result = data.map(item => ({
key: String(item[enumOption.key] ?? item.id ?? item._id),
value: resolveTemplate(enumOption.value, item),
}));
// console.log('Option map for', field.relation, 'first entry:', data[0], 'result key:', result[0]?.key);
return result;
}
return [];
}
export function toGridValueOptions(options: SelectOption[]): { value: string; label: string }[] {
return options.map(opt => ({ value: opt.key, label: opt.value }));
}