39 lines
955 B
TypeScript
39 lines
955 B
TypeScript
// * Other
|
|
import { Model } from "@/back/types/global";
|
|
|
|
/**
|
|
* Extract ids from model relation pivot and format options
|
|
* for a multi select component.
|
|
*/
|
|
export function mapPivotOptions<T extends Model, D extends Model>(
|
|
model: T[],
|
|
data?: D[],
|
|
valueKey?: keyof T,
|
|
locale?: string | null,
|
|
) {
|
|
const options = model?.length
|
|
? model.map((opt) => {
|
|
const raw = opt[valueKey as keyof T] as unknown;
|
|
|
|
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<D extends Model>(
|
|
data?: D[],
|
|
): number[] {
|
|
return data ? data.map((item) => item.id) : [];
|
|
}
|