import { Model } from "@/back/types/global"; /** * Function allowing to extracts Ids from the model relation pivot and format given options to * works in the multi select component */ export function mapPivotOptions< T extends Model[], D extends Record >( /** The model which we want to select options */ model: T, /** Data from the database*/ data?: D[], /** The key name where we find the label of the model */ valueKey?: keyof D, /** If we have a translatable field we pass the current locale */ locale?: string | null ) { const options = (model && model.length) ? model.map((opt) => { const raw = opt[valueKey as keyof typeof opt] as unknown as string; return { value: opt.id.toString(), label: locale && typeof raw === "object" ? raw[locale] : raw }; }) : []; const defaultValue: string[] = data && valueKey ? data.map((item) => { return item.id.toString(); }) : []; return { options, defaultValue }; } /** * Function allowing to extracts Ids from the model relation pivot * @param data * @returns string[]|[] */ export function extractIdsFromDatabasePivotRelation>(data?: D[]): number[]|[] { return data ? data.map((item) => { return item.id; }) : []; }