68 lines
2.1 KiB
JavaScript
68 lines
2.1 KiB
JavaScript
const express = require('express');
|
|
const { spawn } = require('child_process');
|
|
const path = require('path');
|
|
const fs = require('fs');
|
|
|
|
const app = express();
|
|
const port = process.env.PORT || 3006;
|
|
|
|
app.use(express.json({ limit: '50mb' }));
|
|
|
|
// INITIALIZE DATABASE ON START
|
|
const dbScript = path.join(__dirname, 'content_db_manager.py');
|
|
console.log("Initializing database...");
|
|
spawn('python3', [dbScript]);
|
|
|
|
// Helper to run python commands
|
|
function runPython(mode, payload) {
|
|
return new Promise((resolve, reject) => {
|
|
const payloadFile = path.join(__dirname, `payload_${Date.now()}.json`);
|
|
fs.writeFileSync(payloadFile, JSON.stringify(payload));
|
|
|
|
const pythonProcess = spawn('python3', [
|
|
path.join(__dirname, 'content_orchestrator.py'),
|
|
'--mode', mode,
|
|
'--payload_file', payloadFile
|
|
]);
|
|
|
|
let stdout = '';
|
|
let stderr = '';
|
|
|
|
pythonProcess.stdout.on('data', (data) => stdout += data.toString());
|
|
pythonProcess.stderr.on('data', (data) => stderr += data.toString());
|
|
|
|
pythonProcess.on('close', (code) => {
|
|
if (fs.existsSync(payloadFile)) fs.unlinkSync(payloadFile);
|
|
if (code !== 0) {
|
|
console.error(`Python error (code ${code}):`, stderr);
|
|
return reject(stderr);
|
|
}
|
|
try {
|
|
resolve(JSON.parse(stdout));
|
|
} catch (e) {
|
|
reject("Failed to parse Python output: " + stdout);
|
|
}
|
|
});
|
|
});
|
|
}
|
|
|
|
app.post('/api/:mode', async (req, res) => {
|
|
try {
|
|
const result = await runPython(req.params.mode, req.body);
|
|
res.json(result);
|
|
} catch (error) {
|
|
res.status(500).json({ error: error.toString() });
|
|
}
|
|
});
|
|
|
|
// Serve static assets from build (for production)
|
|
if (fs.existsSync(path.join(__dirname, 'dist'))) {
|
|
app.use(express.static(path.join(__dirname, 'dist')));
|
|
app.get('*', (req, res) => {
|
|
res.sendFile(path.join(__dirname, 'dist', 'index.html'));
|
|
});
|
|
}
|
|
|
|
app.listen(port, () => {
|
|
console.log(`Content Engine Server running on port ${port}`);
|
|
}); |