rojects/source/server/routes/files.ts

60 lines
2.6 KiB
TypeScript
Raw Normal View History

import { Router } from 'express';
import { getFileTree, readProjectFile, writeProjectFile, createProjectFile, createProjectDirectory, renameProjectEntry, deleteProjectEntry } from '../storage';
import { requireAuth } from '../middleware/auth';
const router = Router();
router.use(requireAuth);
router.get('/:projectId/tree', (req, res) => {
res.json(getFileTree(req.params.projectId));
});
router.get('/:projectId/*', (req, res) => {
const filePath = (req.params as Record<string, string>)[0];
const content = readProjectFile(req.params.projectId, filePath);
if (content === null) { res.status(404).json({ error: 'Not found' }); return; }
res.type('text/plain').send(content);
});
router.post('/:projectId/create-file', (req, res) => {
const { path: filePath } = req.body as { path: string };
if (!filePath) { res.status(400).json({ error: 'path required' }); return; }
const ok = createProjectFile(req.params.projectId, filePath);
if (!ok) { res.status(409).json({ error: 'Already exists or invalid path' }); return; }
res.json({ ok: true });
});
router.post('/:projectId/create-directory', (req, res) => {
const { path: dirPath } = req.body as { path: string };
if (!dirPath) { res.status(400).json({ error: 'path required' }); return; }
const ok = createProjectDirectory(req.params.projectId, dirPath);
if (!ok) { res.status(409).json({ error: 'Already exists or invalid path' }); return; }
res.json({ ok: true });
});
router.post( '/:projectId/rename', ( req, res ) => {
const { path: oldPath, newName } = req.body as { path: string; newName: string };
if ( !oldPath || !newName ) { res.status( 400 ).json( { error: 'path and newName required' } ); return; }
const ok = renameProjectEntry( req.params.projectId, oldPath, newName );
if ( !ok ) { res.status( 409 ).json( { error: 'Rename failed' } ); return; }
res.json( { ok: true } );
} );
router.post( '/:projectId/delete', ( req, res ) => {
const { path: targetPath } = req.body as { path: string };
if ( !targetPath ) { res.status( 400 ).json( { error: 'path required' } ); return; }
const ok = deleteProjectEntry( req.params.projectId, targetPath );
if ( !ok ) { res.status( 409 ).json( { error: 'Delete failed' } ); return; }
res.json( { ok: true } );
} );
router.put('/:projectId/*', (req, res) => {
const filePath = (req.params as Record<string, string>)[0];
if (typeof req.body !== 'string') { res.status(400).json({ error: 'Content must be text' }); return; }
const ok = writeProjectFile(req.params.projectId, filePath, req.body);
if (!ok) { res.status(403).json({ error: 'Invalid path' }); return; }
res.json({ ok: true });
});
export default router;