All files / src/lib upload.ts

100% Statements 14/14
100% Branches 22/22
100% Functions 2/2
100% Lines 14/14

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        6x                                 12x 12x   12x             12x 3x 3x 2x       10x 12x   12x 6x 6x     4x    
import { config } from './config'
import { ApiError, csrfHeaders, refreshSession, type ApiErrorBody } from './http-client'
 
function isApiErrorBody(value: unknown): value is ApiErrorBody {
  return (
    typeof value === 'object' &&
    value !== null &&
    'status' in value &&
    'message' in value &&
    (value as { status: unknown }).status === 'error'
  )
}
 
/**
 * A dedicated multipart/form-data POST helper — httpClient (lib/http-client.ts)
 * always JSON-stringifies its body and sets `Content-Type: application/json`,
 * which is wrong for a file upload (the browser must set its own
 * `multipart/form-data; boundary=...` Content-Type). Still mirrors the same
 * cookie/CSRF/single-refresh-retry contract as httpClient.
 */
export async function uploadFile<T>(path: string, fieldName: string, file: File, isRetry = false): Promise<T> {
  const formData = new FormData()
  formData.append(fieldName, file)
 
  const response = await fetch(`${config.apiBaseUrl}${path}`, {
    method: 'POST',
    credentials: 'include',
    headers: csrfHeaders('POST'),
    body: formData,
  })
 
  if (response.status === 401 && !isRetry) {
    const refreshed = await refreshSession()
    if (refreshed) {
      return uploadFile<T>(path, fieldName, file, true)
    }
  }
 
  const isJson = response.headers.get('content-type')?.includes('application/json') ?? false
  const data: unknown = isJson ? await response.json() : undefined
 
  if (!response.ok) {
    const errorBody = isApiErrorBody(data) ? data : undefined
    throw new ApiError(response.status, errorBody, errorBody?.message ?? response.statusText)
  }
 
  return data as T
}