File size: 2,583 Bytes
1fe7075
 
 
c7a38a3
1fe7075
 
 
 
 
 
 
 
c7a38a3
 
 
 
 
 
 
1fe7075
 
 
 
 
 
 
 
 
 
c7a38a3
1fe7075
c7a38a3
 
1fe7075
 
c7a38a3
 
1fe7075
 
 
c7a38a3
1fe7075
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
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<CatalogEntry[]> {
    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<number> {
    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`;
  }
}