Reubencf's picture
Fix: Use /data directory for Hugging Face Spaces persistent storage
e099ac1
import { NextRequest, NextResponse } from 'next/server'
import fs from 'fs'
import path from 'path'
// Use /data for Hugging Face Spaces persistent storage
const DATA_DIR = process.env.SPACE_ID
? '/data'
: path.join(process.cwd(), 'public', 'data')
const PUBLIC_DIR = path.join(DATA_DIR, 'public')
// Ensure directories exist
if (!fs.existsSync(DATA_DIR)) {
fs.mkdirSync(DATA_DIR, { recursive: true })
}
if (!fs.existsSync(PUBLIC_DIR)) {
fs.mkdirSync(PUBLIC_DIR, { recursive: true })
}
// Create folder endpoint
export async function POST(request: NextRequest) {
try {
const body = await request.json()
const { folderName, parentPath = '' } = body
if (!folderName) {
return NextResponse.json({ error: 'Folder name required' }, { status: 400 })
}
const folderPath = path.join(PUBLIC_DIR, parentPath, folderName)
// Security check
if (!folderPath.startsWith(PUBLIC_DIR)) {
return NextResponse.json({ error: 'Invalid path' }, { status: 400 })
}
if (fs.existsSync(folderPath)) {
return NextResponse.json({ error: 'Folder already exists' }, { status: 400 })
}
fs.mkdirSync(folderPath, { recursive: true })
return NextResponse.json({
success: true,
path: path.join(parentPath, folderName).replace(/\\/g, '/')
})
} catch (error) {
console.error('Error creating folder:', error)
return NextResponse.json(
{ error: 'Failed to create folder' },
{ status: 500 }
)
}
}
// Delete file endpoint
export async function DELETE(request: NextRequest) {
try {
const searchParams = request.nextUrl.searchParams
const filePath = searchParams.get('path')
if (!filePath) {
return NextResponse.json({ error: 'File path required' }, { status: 400 })
}
const fullPath = path.join(PUBLIC_DIR, filePath)
// Security check
if (!fullPath.startsWith(PUBLIC_DIR)) {
return NextResponse.json({ error: 'Invalid path' }, { status: 400 })
}
if (!fs.existsSync(fullPath)) {
return NextResponse.json({ error: 'File not found' }, { status: 404 })
}
// Delete file or folder
fs.rmSync(fullPath, { recursive: true, force: true })
return NextResponse.json({
success: true,
message: 'File deleted'
})
} catch (error) {
console.error('Error deleting file:', error)
return NextResponse.json(
{ error: 'Failed to delete file' },
{ status: 500 }
)
}
}