38 lines
959 B
TypeScript
38 lines
959 B
TypeScript
import type { DefaultModel } from "@/back/types/global";
|
|
|
|
/**
|
|
* Extract ids from model relation pivot and format options
|
|
* for a multi select component.
|
|
*/
|
|
export function mapPivotOptions<T extends DefaultModel>(
|
|
model: T[],
|
|
data?: DefaultModel[],
|
|
valueKey?: keyof T,
|
|
locale?: string | null,
|
|
) {
|
|
const options = model.length
|
|
? model.map((opt) => {
|
|
const raw = valueKey ? (opt[valueKey] as unknown) : null;
|
|
|
|
return {
|
|
value: opt.id.toString(),
|
|
label:
|
|
locale && typeof raw === "object" && raw !== null
|
|
? (raw as Record<string, string>)[locale]
|
|
: (raw as string),
|
|
};
|
|
})
|
|
: [];
|
|
|
|
const defaultValue = data?.length
|
|
? data.map((item) => item.id.toString())
|
|
: [];
|
|
|
|
return { options, defaultValue };
|
|
}
|
|
|
|
export function extractIdsFromDatabasePivotRelation(
|
|
data?: DefaultModel[],
|
|
): number[] {
|
|
return data ? data.map((item) => item.id) : [];
|
|
}
|