Files
Supervisor/server/api/backup-script.post.ts

58 lines
1.3 KiB
TypeScript

import { exec } from "node:child_process"
import scripts from "../config/backup-script.json"
type BackupScript = {
key: string
label: string
downloadFolders?: string[]
command: string
}
function runCommand(command: string): Promise<string> {
return new Promise((resolve, reject) => {
exec(command, { timeout: 10 * 60 * 1000 }, (error, stdout, stderr) => {
if (error) {
reject(stderr || error.message)
return
}
resolve(stdout || stderr)
})
})
}
export default defineEventHandler(async (event) => {
const body = await readBody<{ key?: string }>(event)
const key = typeof body?.key === "string" ? body.key : null
if (!key) {
throw createError({
statusCode: 400,
statusMessage: "Clé de script manquante"
})
}
const script = (scripts as BackupScript[]).find((item) => item.key === key)
if (!script) {
throw createError({
statusCode: 404,
statusMessage: "Script introuvable"
})
}
try {
const output = await runCommand(script.command)
return {
ok: true,
key: script.key,
label: script.label,
downloadFolders: script.downloadFolders || [],
output: output.trim()
}
} catch (error) {
throw createError({
statusCode: 500,
statusMessage: `Erreur execution script: ${String(error)}`
})
}
})