55 lines
1.7 KiB
TypeScript
55 lines
1.7 KiB
TypeScript
import { NextResponse } from 'next/server'
|
|
import { getErrorMessage, isRecord } from './guards'
|
|
import type { DriveAction } from './types'
|
|
|
|
interface StagingRequestBody {
|
|
stagingId: string
|
|
}
|
|
|
|
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')
|
|
}
|
|
|
|
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)
|
|
|
|
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)
|
|
}
|