This commit is contained in:
eric
2026-03-08 01:10:10 -06:00
parent 0ef4d51406
commit f589b71b19
14 changed files with 2484 additions and 152 deletions

113
app/api/join/route.ts Normal file
View File

@@ -0,0 +1,113 @@
import { NextRequest, NextResponse } from "next/server";
const PB_URL = process.env.POCKETBASE_URL || "https://pocketbase.hackrobot.cn";
const COLLECTION = "solan";
function getOrCreateUserId(): string {
return `user${Date.now()}`;
}
async function getAdminToken(): Promise<string | null> {
const email = process.env.POCKETBASE_EMAIL;
const password = process.env.POCKETBASE_PASSWORD;
if (!email || !password) return null;
const res = await fetch(`${PB_URL}/api/admins/auth-with-password`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ identity: email, password }),
});
if (!res.ok) return null;
const data = await res.json();
return data?.token ?? null;
}
export async function POST(request: NextRequest) {
try {
const userId = getOrCreateUserId();
const body = await request.json();
const formData = body && typeof body === "object" ? body : {};
const {
nickname,
gender,
single,
profession,
intro,
wechat,
education,
graduationYear,
phone,
media: mediaUrl,
} = formData;
// reason=自我介绍, single=感情状态, media=MinIO 上传后的 URL
const record: Record<string, string | number> = {
nickname: nickname || "",
occupation: profession || "",
reason: intro || "",
single: single || "",
wechatId: wechat || "",
gender: gender || "",
education: education || "",
gradYear: graduationYear || "",
phone: phone || "",
user_id: userId,
amount: 0,
order_id: "",
type: "",
};
if (mediaUrl && typeof mediaUrl === "string") {
(record as Record<string, string>)["media"] = mediaUrl;
}
const doCreate = async (authToken?: string) => {
const headers: Record<string, string> = {
"Content-Type": "application/json",
};
if (authToken) headers["Authorization"] = authToken;
return fetch(`${PB_URL}/api/collections/${COLLECTION}/records`, {
method: "POST",
headers,
body: JSON.stringify(record),
});
};
let res = await doCreate();
if (res.status === 403) {
const token = await getAdminToken();
if (token) res = await doCreate(token);
}
if (!res.ok) {
const errText = await res.text();
console.error("PocketBase create error:", res.status, errText);
let errMsg = "提交失败,请稍后重试";
try {
const errJson = JSON.parse(errText);
if (errJson?.message) errMsg = errJson.message;
if (errJson?.data && typeof errJson.data === "object") {
const details = Object.entries(errJson.data)
.map(([k, v]) => `${k}: ${(v as { message?: string })?.message || v}`)
.join("; ");
if (details) errMsg += ` (${details})`;
}
} catch {
if (errText.length < 200) errMsg = errText;
}
return NextResponse.json({ ok: false, error: errMsg }, { status: 500 });
}
return NextResponse.json({ ok: true });
} catch (e) {
const msg = e instanceof Error ? e.message : String(e);
console.error("Join API error:", e);
return NextResponse.json(
{ ok: false, error: `提交失败: ${msg}` },
{ status: 500 }
);
}
}

View File

@@ -0,0 +1,72 @@
import { NextRequest, NextResponse } from "next/server";
import * as Minio from "minio";
// mc alias list myminio: http://minioweb.hackrobot.cn:9035
const MINIO_ENDPOINT = process.env.MINIO_ENDPOINT || "minioweb.hackrobot.cn";
const MINIO_PORT = parseInt(process.env.MINIO_PORT || "9035", 10);
const MINIO_USE_SSL = process.env.MINIO_USE_SSL === "true";
const MINIO_BUCKET = process.env.MINIO_BUCKET || "hackrobot";
const MINIO_ACCESS_KEY = process.env.MINIO_ACCESS_KEY || "6i56HHfg4zPfYItCZtnp";
const MINIO_SECRET_KEY = process.env.MINIO_SECRET_KEY || "vDJCqEit3ejH5UmWKAZnvqhziNfbVsoOlBW12G8Q";
// 公开访问 URLhttps 无端口API 上传用 9035
const MINIO_PUBLIC_URL =
process.env.MINIO_PUBLIC_URL ||
`https://${MINIO_ENDPOINT}/${MINIO_BUCKET}`;
export async function POST(request: NextRequest) {
try {
const form = await request.formData();
const file = form.get("file");
const fileObj =
file instanceof File ? file : file instanceof Blob ? file : null;
if (!fileObj || fileObj.size === 0) {
return NextResponse.json(
{ ok: false, error: "请选择文件" },
{ status: 400 }
);
}
if (fileObj.size > 20 * 1024 * 1024) {
return NextResponse.json(
{ ok: false, error: "文件大小不能超过 20MB" },
{ status: 400 }
);
}
const client = new Minio.Client({
endPoint: MINIO_ENDPOINT,
port: MINIO_PORT,
useSSL: MINIO_USE_SSL,
accessKey: MINIO_ACCESS_KEY,
secretKey: MINIO_SECRET_KEY,
pathStyle: true,
region: process.env.MINIO_REGION || "china",
});
const ext =
(fileObj instanceof File ? fileObj.name : "").split(".").pop() ||
(fileObj.type?.startsWith("video/") ? "mp4" : "jpg");
const objectKey = `joins/${Date.now()}_${Math.random().toString(36).slice(2)}.${ext}`;
const buffer = Buffer.from(await fileObj.arrayBuffer());
const contentType =
(fileObj as File).type || "application/octet-stream";
await client.putObject(MINIO_BUCKET, objectKey, buffer, buffer.length, {
"Content-Type": contentType,
});
const base = MINIO_PUBLIC_URL.replace(/\/$/, "");
const url = `${base}/${objectKey}`;
return NextResponse.json({ ok: true, url });
} catch (e) {
const msg = e instanceof Error ? e.message : String(e);
console.error("Upload media error:", e);
return NextResponse.json(
{ ok: false, error: `上传失败: ${msg}` },
{ status: 500 }
);
}
}