43 lines
1.4 KiB
TypeScript
43 lines
1.4 KiB
TypeScript
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[] {
|
||
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 : [];
|
||
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}".`
|
||
);
|
||
}
|
||
|
||
return data.map(item => ({
|
||
key: String(item[enumOption.key]),
|
||
value: resolveTemplate(enumOption.value, item),
|
||
}));
|
||
}
|
||
|
||
return [];
|
||
}
|
||
|
||
export function toGridValueOptions(options: SelectOption[]): { value: string; label: string }[] {
|
||
return options.map(opt => ({ value: opt.key, label: opt.value }));
|
||
}
|