RealBlocks / server /src /services /storage.ts
incognitolm
2
658aa72
Raw
History Blame Contribute Delete
1.43 kB
import fs from 'fs';
import path from 'path';
const STORAGE_ROOT = process.env.STORAGE_PATH || '/data';
function ensureDir(dir: string) {
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true });
}
}
export async function uploadToStorage(
filePath: string,
data: Buffer,
): Promise<{ success: boolean; message?: string }> {
try {
const fullPath = path.join(STORAGE_ROOT, filePath);
ensureDir(path.dirname(fullPath));
fs.writeFileSync(fullPath, data);
return { success: true };
} catch (error: any) {
console.error('Storage write error:', error.message);
return { success: false, message: error.message };
}
}
export async function downloadFromStorage(filePath: string): Promise<Buffer | null> {
try {
const fullPath = path.join(STORAGE_ROOT, filePath);
if (!fs.existsSync(fullPath)) return null;
return fs.readFileSync(fullPath);
} catch (error: any) {
console.error('Storage read error:', error.message);
return null;
}
}
export async function deleteFromStorage(filePath: string): Promise<{ success: boolean; message?: string }> {
try {
const fullPath = path.join(STORAGE_ROOT, filePath);
if (fs.existsSync(fullPath)) {
fs.unlinkSync(fullPath);
}
return { success: true };
} catch (error: any) {
console.error('Storage delete error:', error.message);
return { success: false, message: error.message };
}
}