Files
blog/write/src/app/api/deploy/route.ts
T
2026-05-21 00:27:35 +08:00

50 lines
1.5 KiB
TypeScript

import { NextRequest, NextResponse } from "next/server";
import { exec } from "child_process";
import { promisify } from "util";
import { BLOG_ROOT } from "@/lib/config";
const execAsync = promisify(exec);
export async function POST(request: NextRequest) {
try {
const body = await request.json();
const { title, slug } = body;
if (!title) {
return NextResponse.json({ error: "Title is required" }, { status: 400 });
}
const commitMsg = `发布: ${title}`;
// git add, commit, push from the blog root
const commands = [
`cd "${BLOG_ROOT}" && git add -A`,
`cd "${BLOG_ROOT}" && git commit -m "${commitMsg.replace(/"/g, '\\"')}"`,
`cd "${BLOG_ROOT}" && git push`,
];
let output = "";
for (const cmd of commands) {
try {
const { stdout, stderr } = await execAsync(cmd);
output += stdout + (stderr || "");
} catch (err: unknown) {
const msg = err instanceof Error ? err.message : String(err);
// git commit may fail if nothing to commit — that's ok
if (msg.includes("nothing to commit") || msg.includes("nothing added")) {
continue;
}
// git push failure is real
throw new Error(`Git command failed: ${msg}`);
}
}
return NextResponse.json({ success: true, output: output.slice(0, 500) });
} catch (error: unknown) {
return NextResponse.json(
{ error: error instanceof Error ? error.message : "Deploy failed" },
{ status: 500 }
);
}
}