import { Injectable } from '@nestjs/common'; import { readFile } from 'node:fs/promises'; import { PrismaService } from '../prisma/prisma.service.js'; import { TILE_VISIBILITIES, type CatalogEntry } from './interfaces/catalog-entry.interface.js'; export const CATALOG_PATH = new URL('../../prisma/catalog.json', import.meta.url); @Injectable() export class CatalogService { constructor(private readonly prisma: PrismaService) {} async load(path: URL | string = CATALOG_PATH): Promise { const entries = (JSON.parse(await readFile(path, 'utf8')) as { tiles: CatalogEntry[] }).tiles; for (const entry of entries) { if (entry.visibility !== undefined && !TILE_VISIBILITIES.includes(entry.visibility)) { throw new Error(`catalog: ${entry.slug} has an unknown visibility "${String(entry.visibility)}"`); } } return entries; } /** * Inserts new tiles and refreshes existing ones in one statement. Entries without an * image are skipped, and a soft-deleted tile is never brought back. */ async seed(entries: CatalogEntry[]): Promise { const rows = entries.filter((entry) => entry.imageUrl); if (!rows.length) return 0; return this.prisma.db.$executeRaw` INSERT INTO tiles (id, slug, name, collection, brand, organization, visibility, surfaces, width_mm, height_mm, image_url, thumbnail_url, assets, render, position, updated_at) SELECT gen_random_uuid(), slug, name, collection, brand, organization, coalesce(visibility, 'public')::tile_visibility, surfaces, "widthMm", "heightMm", "imageUrl", "thumbnailUrl", coalesce(assets, '{}'), coalesce(render, '{}'), position, now() FROM jsonb_to_recordset(${JSON.stringify(rows)}::jsonb) AS entry( slug text, name text, collection text, brand text, organization text, visibility text, surfaces varchar(20)[], "widthMm" int, "heightMm" int, "imageUrl" text, "thumbnailUrl" text, assets jsonb, render jsonb, position int) ON CONFLICT (slug) DO UPDATE SET name = excluded.name, collection = excluded.collection, brand = excluded.brand, organization = excluded.organization, visibility = excluded.visibility, surfaces = excluded.surfaces, width_mm = excluded.width_mm, height_mm = excluded.height_mm, image_url = excluded.image_url, thumbnail_url = excluded.thumbnail_url, assets = excluded.assets, render = excluded.render, position = excluded.position, updated_at = now() WHERE tiles.deleted_at IS NULL`; } }