Files
labelmain/app/api/transfer/[path]/route.ts
2026-03-09 15:03:18 +08:00

175 lines
4.6 KiB
TypeScript

import {
handleDeleteCookie,
handleLoginData,
handleRefreshToken,
} from "@/components/login/libs/cookie"
import { genAccessToken } from "@/components/login/libs/session"
import { headers } from "next/headers"
import {
// NextRequest,
NextResponse,
} from "next/server"
const isParamsValid = (params: {} | null) =>
params !== null && // 排除 null
typeof params === "object" && // 确保是对象类型
!Array.isArray(params) && // 排除数组(可选)
Object.keys(params).length > 0 // 检查是否有自身可枚举属性
export async function POST(req: any) {
try {
const body = await req.json()
let {
url,
data,
options = {},
method = "GET",
isDownload = false,
isLogin = false,
isRefresh = false,
isDeleteCookie = false,
notJson = false,
} = body
if (isDeleteCookie) {
await handleDeleteCookie()
return new NextResponse(
JSON.stringify({
message: "Successfully delete cookie!",
code: 200,
status: true,
}),
{
headers: {
"Content-Type": "application/json",
},
}
)
}
const userData = await genAccessToken(req)
let fetchOptions: any = {}
if (isRefresh) {
if (!userData?.refresh_token) {
return NextResponse.json(
{ message: "Refresh token is empty", code: 406 },
{ status: 200 }
)
}
fetchOptions = {
method,
headers: {
"content-type": "application/json",
},
body: JSON.stringify({
token: userData?.refresh_token,
}),
}
} else {
const authorization = `bearer ${userData?.access_token}`
fetchOptions = {
method,
headers: {
"content-type": "application/json",
authorization: authorization,
},
}
if (method === "POST" || method === "PUT") {
fetchOptions.body = data
} else {
if (isParamsValid(data)) {
let test = ""
for (const [key, value] of Object.entries(data)) {
test += `&${key}=${value}`
}
url += `?${test}`
}
}
}
const isPrefixUrl = url.startsWith("http://") || url.startsWith("https://")
const fetchUrl = isPrefixUrl ? url : `${process.env.NEXT_PUBLIC_URL}${url}`
const res = await fetch(fetchUrl, fetchOptions)
if (res?.status !== 200) {
let error = ""
if (res.headers.get("Content-Type")?.includes("application/json")) {
const data = await res.json()
error = data?.message || ""
} else {
error = await res.text()
}
return NextResponse.json({ message: error }, { status: res?.status })
}
if (
options?.responseType === "blob" ||
options?.responseType === "arraybuffer" ||
isDownload
) {
const blob = await res.blob()
const buffer = await blob.arrayBuffer()
return new NextResponse(buffer, {
headers: {
"Content-Type": blob.type,
"x-real-name": res?.headers?.get("content-disposition") || "",
},
})
} else if (!notJson) {
try {
const data = await (res.headers
.get("Content-Type")
?.includes("application/json")
? res.json()
: res.text())
if (isLogin) {
const header = await headers()
let clientIP =
header.get("x-forwarded-for")?.split(",")[0] ||
req?.socket?.remoteAddress
// ip v6地址
if (clientIP.startsWith("::")) {
clientIP = clientIP.slice(7)
}
const newData = await handleLoginData({
clientIP: clientIP,
fingerprint: body.fingerprint,
data,
})
return new NextResponse(JSON.stringify(newData), {
headers: {
"Content-Type": "application/json",
},
})
}
if (isRefresh) {
const newData = await handleRefreshToken({
userData,
data,
})
return new NextResponse(JSON.stringify(newData), {
headers: {
"Content-Type": "application/json",
},
})
}
return new NextResponse(JSON.stringify(data), {
headers: {
"Content-Type": "application/json",
},
})
} catch (err) {
return NextResponse.json({ error: err }, { status: 500 })
}
} else {
return res
}
} catch (err) {
return NextResponse.json({ error: err }, { status: 500 })
}
}