(config: Sorting<L> & Naming, idOrIndex: string | undefined, listFunction: ListDataFunction<L>)
| 20 | export async function stringTranslateToId<L extends object>(config: Sorting<L> & Naming, idOrIndex: string, listFunction: ListDataFunction<L>): Promise<string> |
| 21 | export async function stringTranslateToId<L extends object>(config: Sorting<L> & Naming, idOrIndex: string | undefined, listFunction: ListDataFunction<L>): Promise<string | undefined> |
| 22 | export async function stringTranslateToId<L extends object>(config: Sorting<L> & Naming, idOrIndex: string | undefined, listFunction: ListDataFunction<L>): Promise<string | undefined> { |
| 23 | if (!idOrIndex) { |
| 24 | return undefined |
| 25 | } |
| 26 | |
| 27 | const primaryKeyName = config.primaryKeyName |
| 28 | if (!isIndexArgument(idOrIndex)) { |
| 29 | // idOrIndex isn't a valid index so has to be an id (or bad) |
| 30 | return idOrIndex |
| 31 | } |
| 32 | |
| 33 | const index = Number.parseInt(idOrIndex) |
| 34 | |
| 35 | const items = sort(await listFunction(), config.sortKeyName) |
| 36 | if (index > items.length) { |
| 37 | throw Error(`invalid index ${index} (enter an id or index between 1 and ${items.length} inclusive)`) |
| 38 | } |
| 39 | const matchingItem: L = items[index - 1] |
| 40 | if (!(primaryKeyName in matchingItem)) { |
| 41 | throw Error(`did not find key ${primaryKeyName} in data`) |
| 42 | } |
| 43 | const pk = matchingItem[primaryKeyName] |
| 44 | if (typeof pk === 'string') { |
| 45 | return pk |
| 46 | } |
| 47 | throw Error(`invalid type ${typeof pk} for primary key` + |
| 48 | ` ${primaryKeyName} in ${JSON.stringify(matchingItem)}`) |
| 49 | } |
| 50 | |
| 51 | export function convertToId<L>(itemIdOrIndex: string, primaryKeyName: Extract<keyof L, string>, sortedList: L[]): string | false { |
| 52 | if (itemIdOrIndex.length === 0) { |
no test coverage detected