All files / src/lib dev-sample-bootstrap.ts

38.23% Statements 13/34
27.27% Branches 3/11
40% Functions 2/5
36.66% Lines 11/30

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86                    1x   1x 1x 1x   1x             2x 2x 20x 20x   2x       1x                                                                                                          
import { existsSync, statSync } from "node:fs";
import { basename, join } from "node:path";
import type { Database } from "@/lib/db";
import { generateId } from "@/lib/id";
import { withTransaction } from "@/lib/transactions";
import { SAMPLE_ITEMS, type SampleItem } from "@/features/onboarding/sampleData";
import { CollectionRepository } from "@/server/repositories/implementations/CollectionRepository";
import { ItemRepository } from "@/server/repositories/implementations/ItemRepository";
import { PhotoRepository } from "@/server/repositories/implementations/PhotoRepository";
 
const DEV_SAMPLE_COLLECTION_NAME = "Sample collection";
const DEV_SAMPLE_COLLECTION_DESCRIPTION =
  "A small generated collection for local development.";
const DEV_SAMPLE_ITEM_COUNT = 5;
const DEMO_SEED_PREFIX = "demo-seed-placeholder/";
 
const inFlight = new Map<string, Promise<void>>();
 
export function selectRandomSampleItems(
  items: readonly SampleItem[],
  count: number,
  random: () => number = Math.random,
): SampleItem[] {
  const shuffled = [...items];
  for (let i = shuffled.length - 1; i > 0; i--) {
    const j = Math.floor(random() * (i + 1));
    [shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
  }
  return shuffled.slice(0, Math.min(count, shuffled.length));
}
 
export async function ensureDevSampleCollection(db: Database, userId: string): Promise<void> {
  Eif (process.env.NODE_ENV !== "development" || process.env.AUTH_BYPASS !== "1") return;
 
  const existing = inFlight.get(userId);
  if (existing) return existing;
 
  const next = bootstrapDevSampleCollection(db, userId).finally(() => {
    inFlight.delete(userId);
  });
  inFlight.set(userId, next);
  return next;
}
 
async function bootstrapDevSampleCollection(db: Database, userId: string): Promise<void> {
  await withTransaction(
    db,
    async (tx) => {
      const collectionRepo = new CollectionRepository(tx);
      const existingCollections = await collectionRepo.findByOwner(userId);
      if (existingCollections.length > 0) return;
 
      const collection = await collectionRepo.create({
        id: generateId("col"),
        ownerId: userId,
        name: DEV_SAMPLE_COLLECTION_NAME,
        description: DEV_SAMPLE_COLLECTION_DESCRIPTION,
      });
 
      const itemRepo = new ItemRepository(tx);
      const photoRepo = new PhotoRepository(tx);
      const samples = selectRandomSampleItems(SAMPLE_ITEMS, DEV_SAMPLE_ITEM_COUNT);
 
      for (const sample of samples) {
        const item = await itemRepo.create({
          collectionId: collection.id,
          name: sample.name,
        });
        const filename = basename(sample.imageSrc);
        const localPath = join(process.cwd(), "public", "onboarding", filename);
        await photoRepo.create({
          itemId: item.id,
          collectionId: collection.id,
          blobKey: `${DEMO_SEED_PREFIX}${filename}`,
          filename,
          mimeType: "image/webp",
          fileSize: existsSync(localPath) ? statSync(localPath).size : null,
          uploadedBy: userId,
          isHero: true,
        });
      }
    },
    { op: "dev_sample_bootstrap", ctx: { curatorId: userId } },
  );
}