All files / src/server/files stored.ts

100% Statements 16/16
83.33% Branches 10/12
100% Functions 3/3
100% Lines 16/16

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              3x                     47x       47x 45x   2x 2x                           64x 5x   64x 64x   2x 2x   2x   62x 3x   62x    
// What the features that store uploaded files share: the name kept for a
// file, and storing a file around a database write.
import type { Logger, LogEvent } from '#/server/log/log'
import { deleteStoredFiles } from './delete'
import type { FileStorage } from './storage'
 
/** The longest stored file name, in characters. */
const MAX_FILENAME_LENGTH = 100
 
/**
 * The browser's file name without control characters, at most 100 long.
 * Without a usable name it is `<fallback>.pdf` or `<fallback>.jpg`.
 */
export function uploadFilename(
  name: string,
  contentType: string,
  fallback: string,
): string {
  const cleaned = name
    .replace(/\p{Cc}/gu, '')
    .trim()
    .slice(-MAX_FILENAME_LENGTH)
  if (cleaned !== '') {
    return cleaned
  }
  const extension = contentType === 'application/pdf' ? 'pdf' : 'jpg'
  return `${fallback}.${extension}`
}
 
/**
 * Runs a database write after storing a file; removes the file if the write
 * throws or doesn't apply. A failed removal is logged as `failureEvent`.
 */
export async function withStoredFile<T>(
  deps: { storage: FileStorage; log: Logger },
  failureEvent: LogEvent,
  key: string | undefined,
  write: () => Promise<T>,
  applied: (result: T) => boolean,
): Promise<T> {
  const remove = () =>
    deleteStoredFiles(deps.storage, deps.log, [key ?? ''], failureEvent)
  let result: T
  try {
    result = await write()
  } catch (error) {
    Eif (key) {
      await remove()
    }
    throw error
  }
  if (key && !applied(result)) {
    await remove()
  }
  return result
}