fix: harden upload resilience and contracts
This commit is contained in:
+32
-3
@@ -1,4 +1,5 @@
|
||||
import { isRecord } from './guards'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { getErrorMessage, isRecord } from './guards'
|
||||
import type { DriveAction } from './types'
|
||||
|
||||
interface StagingRequestBody {
|
||||
@@ -9,6 +10,21 @@ interface DriveRequestBody extends StagingRequestBody {
|
||||
action: DriveAction
|
||||
}
|
||||
|
||||
const UPLOAD_LOCK_ERROR = 'Un upload est deja en cours pour ce dossier. Patientez quelques secondes.'
|
||||
|
||||
export function uploadErrorResponse(error: unknown, status: number, fallback?: string) {
|
||||
const message = getErrorMessage(error, fallback)
|
||||
return NextResponse.json({ success: false, error: message }, { status })
|
||||
}
|
||||
|
||||
export function uploadErrorMessageResponse(message: string, status: number) {
|
||||
return NextResponse.json({ success: false, error: message }, { status })
|
||||
}
|
||||
|
||||
export function uploadLockConflictResponse() {
|
||||
return uploadErrorMessageResponse(UPLOAD_LOCK_ERROR, 409)
|
||||
}
|
||||
|
||||
export function parseStagingRequestBody(value: unknown): StagingRequestBody {
|
||||
if (!isRecord(value) || typeof value.stagingId !== 'string' || value.stagingId.trim() === '') {
|
||||
throw new Error('stagingId manquant')
|
||||
@@ -17,9 +33,22 @@ export function parseStagingRequestBody(value: unknown): StagingRequestBody {
|
||||
return { stagingId: value.stagingId }
|
||||
}
|
||||
|
||||
export async function readStagingRequestBody(req: Request): Promise<StagingRequestBody> {
|
||||
const body: unknown = await req.json()
|
||||
return parseStagingRequestBody(body)
|
||||
}
|
||||
|
||||
export function parseDriveRequestBody(value: unknown): DriveRequestBody {
|
||||
const { stagingId } = parseStagingRequestBody(value)
|
||||
const action = isRecord(value) && value.action === 'replace' ? 'replace' : 'new'
|
||||
|
||||
return { stagingId, action }
|
||||
if (!isRecord(value) || (value.action !== 'new' && value.action !== 'replace')) {
|
||||
throw new Error('Action Drive invalide')
|
||||
}
|
||||
|
||||
return { stagingId, action: value.action }
|
||||
}
|
||||
|
||||
export async function readDriveRequestBody(req: Request): Promise<DriveRequestBody> {
|
||||
const body: unknown = await req.json()
|
||||
return parseDriveRequestBody(body)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user