gongxiangp2/lib/safe-json.ts
chenpei 4e89b57798 feat(upload): optimize upload UI and performance
- Expand batch upload list area and optimize preview image layout
- Improve upload speed tracking and display (server-side & client-side)
- Reduce network detection log noise
- Optimize Docker build process (caching, env validation)
- Add shadow environment deployment support
2026-01-28 15:07:50 +08:00

114 lines
3.1 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* R44修复:安全的 JSON 解析工具函数
*
* 用途:
* 1. 安全解析 JSON 字符串,失败时返回默认值而非抛出异常
* 2. 安全解析 request.json(),提供更友好的错误信息
*/
import { NextRequest, NextResponse } from 'next/server'
/**
* 安全解析 JSON 字符串
* @param jsonString 要解析的 JSON 字符串
* @param fallback 解析失败时的默认值
* @param logError 是否记录错误日志(默认 true)
* @returns 解析结果或默认值
*/
export function safeJsonParse<T>(
jsonString: string,
fallback: T,
logError: boolean = true
): T {
try {
return JSON.parse(jsonString)
} catch (error) {
if (logError) {
console.warn('[SafeJSON] JSON 解析失败:', error)
}
return fallback
}
}
/**
* 安全解析 JSON 字符串,返回结果和错误信息
* @param jsonString 要解析的 JSON 字符串
* @returns { data: T | null, error: string | null }
*/
export function safeJsonParseWithError<T>(
jsonString: string
): { data: T | null; error: string | null } {
try {
const data = JSON.parse(jsonString) as T
return { data, error: null }
} catch (error) {
const errorMessage = error instanceof Error ? error.message : '未知错误'
return { data: null, error: `JSON 解析失败: ${errorMessage}` }
}
}
/**
* 安全解析请求体 JSON
* 如果解析失败,返回错误响应;否则返回解析后的数据
*
* @param request NextRequest 对象
* @returns { data: T, response: null } 或 { data: null, response: NextResponse }
*/
export async function safeParseRequestJson<T>(
request: NextRequest
): Promise<{ data: T; response: null } | { data: null; response: NextResponse }> {
try {
const data = await request.json() as T
return { data, response: null }
} catch (error) {
console.warn('[SafeJSON] 请求体 JSON 解析失败:', error)
return {
data: null,
response: NextResponse.json(
{ error: '请求数据格式错误,请确保发送的是有效的 JSON' },
{ status: 400 }
)
}
}
}
/**
* 验证并解析请求体 JSON(带类型验证)
*
* @param request NextRequest 对象
* @param requiredFields 必需的字段列表
* @returns 解析结果或错误响应
*/
export async function validateAndParseRequestJson<T extends Record<string, any>>(
request: NextRequest,
requiredFields: (keyof T)[]
): Promise<{ data: T; response: null } | { data: null; response: NextResponse }> {
// 先解析 JSON
const parseResult = await safeParseRequestJson<T>(request)
if (parseResult.response) {
return parseResult
}
// 验证必需字段
const data = parseResult.data
const missingFields: string[] = []
for (const field of requiredFields) {
if (data[field] === undefined || data[field] === null) {
missingFields.push(String(field))
}
}
if (missingFields.length > 0) {
return {
data: null,
response: NextResponse.json(
{ error: `缺少必需的字段: ${missingFields.join(', ')}` },
{ status: 400 }
)
}
}
return { data, response: null }
}