47 lines
1.4 KiB
TypeScript
47 lines
1.4 KiB
TypeScript
import type { H3Event } from 'h3'
|
|
|
|
interface LinkValue {
|
|
value: string | null
|
|
}
|
|
|
|
export interface ShelfBookRow {
|
|
id: number
|
|
title: string | null
|
|
title_german: string | null
|
|
authors: LinkValue[]
|
|
}
|
|
|
|
interface Field {
|
|
name: string
|
|
link_row_table_id?: number
|
|
}
|
|
|
|
let booksTable: string | null = null
|
|
|
|
/** The books table, taken from the wishlist table's `books` link field. */
|
|
export async function wishlistBooksTable(event: H3Event): Promise<string> {
|
|
if (!booksTable) {
|
|
const fields = await listFields<Field>(event, wishlistTable(event))
|
|
const id = fields.find(field => field.name === 'books')?.link_row_table_id
|
|
if (!id) {
|
|
throw createError({ statusCode: 500, statusMessage: 'The wishlist table has no "books" link field' })
|
|
}
|
|
booksTable = String(id)
|
|
}
|
|
return booksTable
|
|
}
|
|
|
|
export function toShelfBook(row: ShelfBookRow): WishlistShelfBook {
|
|
return {
|
|
id: row.id,
|
|
title: row.title_german?.trim() || (row.title ?? '').trim(),
|
|
authors: (row.authors ?? []).map(({ value }) => value?.trim()).filter((value): value is string => !!value)
|
|
}
|
|
}
|
|
|
|
/** Books from the books table matching a Baserow filter, e.g. `{ filter__read__boolean: true }` */
|
|
export async function listShelfBooks(event: H3Event, filters: Record<string, unknown>): Promise<WishlistShelfBook[]> {
|
|
const rows = await listRows<ShelfBookRow>(event, await wishlistBooksTable(event), filters)
|
|
return rows.map(toShelfBook).filter(book => book.title)
|
|
}
|