Update api.copy-files.ts

This commit is contained in:
Yaqub Mahmoud 2025-01-28 16:30:08 +09:00
parent 4241f10d08
commit a066f5a0b7

View File

@ -1,36 +1,70 @@
// api/copy-files.ts
import express from 'express';
// server.ts
import http from 'http';
import { parse as parseUrl } from 'url';
import fs from 'fs/promises';
import path from 'path';
const router = express.Router();
interface FileContent {
type: string;
content: string;
}
router.post('/copy-files', async (req, res) => {
try {
const { files, targetDirectory } = req.body;
interface CopyFilesRequest {
files: Record<string, FileContent>;
targetDirectory: string;
}
// ensure target directory exists
await fs.mkdir(targetDirectory, { recursive: true });
const server = http.createServer(async (req, res) => {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'POST, OPTIONS');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
// copy each file
for (const [filePath, dirent] of Object.entries(files)) {
if (dirent?.type === 'file' && dirent.content) {
const fullPath = path.join(targetDirectory, filePath.startsWith('/') ? filePath.slice(1) : filePath);
const dirPath = path.dirname(fullPath);
if (req.method === 'OPTIONS') {
res.writeHead(204);
res.end();
// ensure directory exists
await fs.mkdir(dirPath, { recursive: true });
return;
}
// write file
await fs.writeFile(fullPath, dirent.content);
const parsedUrl = parseUrl(req.url || '', true);
if (parsedUrl.pathname === '/copy-files' && req.method === 'POST') {
try {
let body = '';
for await (const chunk of req) {
body += chunk;
}
}
res.json({ success: true });
} catch (error) {
console.error('Error copying files:', error);
res.status(500).json({ error: 'Failed to copy files' });
const { files, targetDirectory } = JSON.parse(body) as CopyFilesRequest;
await fs.mkdir(targetDirectory, { recursive: true });
for (const [filePath, dirent] of Object.entries(files)) {
if (dirent?.type === 'file' && dirent.content) {
const fullPath = path.join(targetDirectory, filePath.startsWith('/') ? filePath.slice(1) : filePath);
const dirPath = path.dirname(fullPath);
await fs.mkdir(dirPath, { recursive: true });
await fs.writeFile(fullPath, dirent.content);
}
}
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ success: true }));
} catch (error) {
console.error('Error copying files:', error);
res.writeHead(500, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'Failed to copy files' }));
}
} else {
res.writeHead(404, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'Not found' }));
}
});
export default router;
const PORT = process.env.PORT || 3001;
server.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}`);
});