All files / web/src/lib image-storage.ts

0% Statements 0/61
0% Branches 0/1
0% Functions 0/1
0% Lines 0/61

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                                                                                                                           
import { existsSync, mkdirSync, writeFileSync } from 'fs'
import { readFile } from 'fs/promises'
import { dirname, join } from 'path'

export type ImageStorageTarget =
  | { type: 'static'; relativePath: string }
  | { type: 'persistent'; category: string; filename: string }

const PUBLIC_DIR = join(process.cwd(), 'public')
const PERSISTENT_DIR = join(process.cwd(), 'data', 'generated-images')

function resolvePath(target: ImageStorageTarget): string {
  if (target.type === 'static') {
    return join(PUBLIC_DIR, target.relativePath)
  }
  return join(PERSISTENT_DIR, target.category, target.filename)
}

function resolvePublicUrl(target: ImageStorageTarget): string {
  if (target.type === 'static') {
    return `/${target.relativePath}`
  }
  return `/api/images/${target.category}/${target.filename}`
}

export function storeImage(
  target: ImageStorageTarget,
  buffer: Buffer
): { publicUrl: string; sizeBytes: number } {
  const filePath = resolvePath(target)
  mkdirSync(dirname(filePath), { recursive: true })
  writeFileSync(filePath, buffer)
  return { publicUrl: resolvePublicUrl(target), sizeBytes: buffer.byteLength }
}

export function imageExists(target: ImageStorageTarget): boolean {
  return existsSync(resolvePath(target))
}

/** Read a static image from the public directory by its relative path. */
export async function readStaticImage(relativePath: string): Promise<Buffer | null> {
  const filePath = join(PUBLIC_DIR, relativePath)
  try {
    return await readFile(filePath)
  } catch {
    return null
  }
}

export async function readPersistentImage(
  category: string,
  filename: string
): Promise<{ buffer: Buffer; sizeBytes: number } | null> {
  const filePath = join(PERSISTENT_DIR, category, filename)
  try {
    const buffer = await readFile(filePath)
    return { buffer, sizeBytes: buffer.byteLength }
  } catch {
    return null
  }
}