Create server.js
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103// @ts-nocheckimport express from 'express';import cors from 'cors';import multer from 'multer';import { uploadFile } from '@huggingface/hub';import path from 'path';import { fileURLToPath } from 'url';import dotenv from 'dotenv';dotenv.config()// Fix __dirname for ES Modulesconst __filename = fileURLToPath(import.meta.url);const __dirname = path.dirname(__filename);
const app = express();// Hugging Face Spaces requires port 7860const port = process.env.PORT || 7860;
// Middlewareapp.use(cors());app.use(express.json());
// Configure Multer for memory storage (file buffer)const storage = multer.memoryStorage();const upload = multer({ storage: storage });
// SERVER CONFIGURATION// PRIORITY: Environment Variable > Hardcoded Fallbackconst SERVER_CONFIG = { TOKEN: process.env.HF_TOKEN || '', REPO: process.env.HF_REPO || 'TwanAPI/DataTwan', TYPE: 'dataset'};
// --- API ROUTES ---
// Upload Endpointapp.post('/api/upload', upload.single('file'), async (req, res) => { try { const file = req.file; const filePath = req.body.path;
if (!file) { return res.status(400).json({ error: 'No file provided' }); }
if (!filePath) { return res.status(400).json({ error: 'No file path provided' }); }
console.log(`[SERVER] Uploading: ${filePath} (${file.size} bytes)`);
// Upload to Hugging Face const response = await uploadFile({ credentials: { accessToken: SERVER_CONFIG.TOKEN, }, repo: { type: SERVER_CONFIG.TYPE, name: SERVER_CONFIG.REPO }, file: { path: filePath, content: new Blob([file.buffer]), }, });
const commitHash = response.commit.oid; const urlPrefix = "https://huggingface.co/datasets"; const publicUrl = `${urlPrefix}/${SERVER_CONFIG.REPO}/blob/${commitHash}/${filePath}`;
console.log(`[SERVER] Success: ${publicUrl}`);
res.json({ success: true, url: publicUrl });
} catch (error) { console.error('[SERVER] Upload Error:', error); res.status(500).json({ success: false, error: error.message || 'Internal Server Error' }); }});
// --- SERVE FRONTEND (Production) ---
// Serve static files from the React build directoryapp.use(express.static(path.join(__dirname, 'dist')));
// Handle React Routing (SPA) - Return index.html for any unknown routeapp.get('*', (req, res) => { res.sendFile(path.join(__dirname, 'dist', 'index.html'));});
// Start Serverapp.listen(port, () => { console.log(`--------------------------------------------------`); console.log(`✅ Server running on port ${port}`); console.log(` Target Repo: ${SERVER_CONFIG.REPO}`); console.log(`--------------------------------------------------`);});server.jsAdded+103