完成评查点分组的增删改
This commit is contained in:
+213
-23
@@ -21,8 +21,9 @@ export interface PostgrestParams {
|
||||
* 打印 PostgREST 查询日志
|
||||
* @param endpoint 端点
|
||||
* @param params 参数
|
||||
* @param method HTTP 方法
|
||||
*/
|
||||
function logPostgrestQuery(endpoint: string, params?: QueryParams): void {
|
||||
function logPostgrestQuery(endpoint: string, params?: QueryParams, method: string = 'GET'): void {
|
||||
if (process.env.NODE_ENV !== 'production') {
|
||||
// const baseUrl = 'http://172.16.0.119:9000/admin';
|
||||
// const baseUrl = 'http://172.18.0.100:3000';
|
||||
@@ -32,6 +33,7 @@ function logPostgrestQuery(endpoint: string, params?: QueryParams): void {
|
||||
const normalizedEndpoint = endpoint.startsWith('/') ? endpoint.substring(1) : endpoint;
|
||||
|
||||
console.log('\n📦 PostgREST 查询日志 ========================');
|
||||
console.log(`📦 HTTP 方法: ${method}`);
|
||||
console.log(`📦 API 端点: ${baseUrl}/${normalizedEndpoint}`);
|
||||
|
||||
if (params && Object.keys(params).length > 0) {
|
||||
@@ -74,7 +76,7 @@ function logPostgrestQuery(endpoint: string, params?: QueryParams): void {
|
||||
console.log(`\n📦 可读URL: ${baseUrl}/${normalizedEndpoint}${readableQueryString ? '?' + readableQueryString : ''}`);
|
||||
|
||||
// 格式化查询为 PostgreSQL 风格的查询
|
||||
let postgrestQuery = `SELECT `;
|
||||
let postgrestQuery = `${method.toUpperCase()} `;
|
||||
|
||||
if (params.select && typeof params.select === 'string') {
|
||||
postgrestQuery += params.select.replace(/\s+/g, ' ').trim();
|
||||
@@ -251,7 +253,7 @@ export async function postgrestGet<T>(endpoint: string, params?: PostgrestParams
|
||||
const apiEndpoint = endpoint.startsWith('/') ? endpoint.substring(1) : endpoint;
|
||||
|
||||
// 打印查询信息
|
||||
logPostgrestQuery(apiEndpoint, queryParams);
|
||||
logPostgrestQuery(apiEndpoint, queryParams, 'GET');
|
||||
|
||||
// 提取并移除自定义头部参数
|
||||
const headers: Record<string, string> = params?.headers || {};
|
||||
@@ -285,9 +287,96 @@ export async function postgrestGet<T>(endpoint: string, params?: PostgrestParams
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理 PostgreSQL 特定错误
|
||||
* @param error 错误对象或消息
|
||||
* @param responseText 原始响应文本
|
||||
* @returns 格式化的错误信息
|
||||
*/
|
||||
function handlePostgresError(error: unknown, responseText?: string): { message: string, status?: number } {
|
||||
let errorMessage = error instanceof Error ? error.message : String(error);
|
||||
let statusCode: number | undefined = undefined;
|
||||
|
||||
// 如果有原始响应文本,尝试从中提取更详细的错误信息
|
||||
if (responseText) {
|
||||
try {
|
||||
const errorData = JSON.parse(responseText);
|
||||
|
||||
// 处理 PostgreSQL 错误码
|
||||
if (errorData.code) {
|
||||
switch (errorData.code) {
|
||||
case '23505': // 唯一约束冲突
|
||||
errorMessage = '记录已存在,无法创建重复数据';
|
||||
if (errorData.details) {
|
||||
// 尝试提取冲突的字段名
|
||||
const match = errorData.details.match(/Key \((.+?)\)=/);
|
||||
if (match && match[1]) {
|
||||
const field = match[1];
|
||||
errorMessage = `${field} 已存在,请使用不同的值`;
|
||||
}
|
||||
}
|
||||
statusCode = 409; // Conflict
|
||||
break;
|
||||
|
||||
case '23503': // 外键约束失败
|
||||
errorMessage = '引用的记录不存在';
|
||||
if (errorData.details) {
|
||||
// 尝试提取外键字段
|
||||
const match = errorData.details.match(/Key \((.+?)\)=/);
|
||||
if (match && match[1]) {
|
||||
const field = match[1];
|
||||
errorMessage = `所引用的 ${field} 不存在或无效`;
|
||||
}
|
||||
}
|
||||
statusCode = 400; // Bad Request
|
||||
break;
|
||||
|
||||
case '42P01': // 表不存在
|
||||
errorMessage = '所请求的数据表不存在';
|
||||
statusCode = 404; // Not Found
|
||||
break;
|
||||
|
||||
case '42703': // 列不存在
|
||||
errorMessage = '所引用的字段不存在';
|
||||
if (errorData.details) {
|
||||
const match = errorData.details.match(/column "(.+?)"/);
|
||||
if (match && match[1]) {
|
||||
const column = match[1];
|
||||
errorMessage = `字段 "${column}" 不存在`;
|
||||
}
|
||||
}
|
||||
statusCode = 400; // Bad Request
|
||||
break;
|
||||
|
||||
default:
|
||||
// 使用 PostgreSQL 提供的错误消息
|
||||
if (errorData.message) {
|
||||
errorMessage = errorData.message;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// 处理 HTTP 状态码
|
||||
if (errorData.status) {
|
||||
statusCode = errorData.status;
|
||||
}
|
||||
|
||||
} catch (e) {
|
||||
console.error('解析错误响应失败:', e);
|
||||
// 如果解析失败,尝试直接使用响应文本
|
||||
if (responseText && responseText.length < 200) {
|
||||
errorMessage = responseText;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return { message: errorMessage, status: statusCode };
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送 POST 请求到 PostgresREST 接口
|
||||
* @param endpoint 端点
|
||||
* @param endpoint 端点(表名)
|
||||
* @param data 请求体数据
|
||||
* @returns 响应数据
|
||||
*/
|
||||
@@ -297,46 +386,143 @@ export async function postgrestPost<T, D = Record<string, unknown>>(endpoint: st
|
||||
const apiEndpoint = endpoint.startsWith('/') ? endpoint.substring(1) : endpoint;
|
||||
|
||||
// 打印查询信息(POST请求只打印端点)
|
||||
logPostgrestQuery(apiEndpoint);
|
||||
logPostgrestQuery(apiEndpoint, undefined, 'POST');
|
||||
|
||||
const response = await apiRequest<T>(
|
||||
apiEndpoint,
|
||||
{
|
||||
method: 'POST',
|
||||
body: JSON.stringify(data),
|
||||
headers: {
|
||||
'Prefer': 'return=representation'
|
||||
// 预处理数据,确保所有字段类型符合 PostgreSQL 要求
|
||||
const processedData = preprocessData(data as Record<string, unknown>);
|
||||
|
||||
// 确保数据是合法的JSON对象
|
||||
const requestBody = JSON.stringify(processedData);
|
||||
console.log(`准备发送 PostgreSQL 插入请求到: ${apiEndpoint}`);
|
||||
console.log(`请求体: ${requestBody}`);
|
||||
|
||||
try {
|
||||
const response = await apiRequest<T>(
|
||||
apiEndpoint,
|
||||
{
|
||||
method: 'POST',
|
||||
body: requestBody,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Accept': 'application/json',
|
||||
'Prefer': 'return=representation'
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
if (response.error) {
|
||||
console.error(`POST请求失败: ${response.error}`);
|
||||
throw new Error(response.error);
|
||||
}
|
||||
);
|
||||
|
||||
if (response.error) {
|
||||
throw new Error(response.error);
|
||||
|
||||
console.log(`POST请求成功,响应: `, response.data);
|
||||
return { data: response.data as T };
|
||||
} catch (error) {
|
||||
// 捕获并处理 API 请求错误
|
||||
let errorText = '';
|
||||
|
||||
// 如果错误对象中包含响应文本,尝试提取更详细的错误信息
|
||||
if (error instanceof Error && 'responseText' in error) {
|
||||
errorText = (error as {responseText: string}).responseText;
|
||||
}
|
||||
|
||||
// 处理 PostgreSQL 特定错误
|
||||
const pgError = handlePostgresError(error, errorText);
|
||||
|
||||
console.error(`POST请求错误: ${pgError.message}`);
|
||||
return {
|
||||
error: pgError.message,
|
||||
status: pgError.status || 500
|
||||
};
|
||||
}
|
||||
|
||||
return { data: response.data as T };
|
||||
} catch (error) {
|
||||
console.error(`POST请求处理错误: ${error instanceof Error ? error.message : String(error)}`);
|
||||
const apiError = handleApiError(error);
|
||||
return { error: apiError.message, status: apiError.status };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 预处理数据,确保类型与 PostgreSQL 兼容
|
||||
* @param data 原始数据
|
||||
* @returns 处理后的数据
|
||||
*/
|
||||
function preprocessData(data: Record<string, unknown>): Record<string, unknown> {
|
||||
const processed: Record<string, unknown> = {};
|
||||
|
||||
for (const [key, value] of Object.entries(data)) {
|
||||
// 确保 null 值被正确处理
|
||||
if (value === null) {
|
||||
processed[key] = null;
|
||||
continue;
|
||||
}
|
||||
|
||||
// 处理字符串可能被错误解析为数字的情况
|
||||
if (typeof value === 'string' && /^\d+$/.test(value) && key !== 'code' && !key.endsWith('_id')) {
|
||||
// 对于可能需要保持字符串格式的值,我们不进行数字转换
|
||||
processed[key] = value;
|
||||
}
|
||||
// 将字符串 'true'/'false' 转为布尔值
|
||||
else if (typeof value === 'string' && (value.toLowerCase() === 'true' || value.toLowerCase() === 'false')) {
|
||||
processed[key] = value.toLowerCase() === 'true';
|
||||
}
|
||||
// 尝试转换 '0'/'1' 为 boolean (如果字段名暗示是布尔值)
|
||||
else if (typeof value === 'string' && (value === '0' || value === '1') &&
|
||||
(key.startsWith('is_') || key.startsWith('has_') || key.endsWith('_enabled'))) {
|
||||
processed[key] = value === '1';
|
||||
}
|
||||
// 对于ID字段确保使用正确的类型
|
||||
else if ((key === 'id' || key.endsWith('_id') || key === 'pid') && value !== undefined) {
|
||||
try {
|
||||
const numValue = Number(value);
|
||||
if (!isNaN(numValue)) {
|
||||
processed[key] = numValue;
|
||||
} else {
|
||||
processed[key] = value;
|
||||
}
|
||||
} catch {
|
||||
processed[key] = value;
|
||||
}
|
||||
}
|
||||
// 其他值保持不变
|
||||
else {
|
||||
processed[key] = value;
|
||||
}
|
||||
}
|
||||
|
||||
return processed;
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送 PUT 请求到 PostgresREST 接口
|
||||
* @param endpoint 端点
|
||||
* @param data 请求体数据
|
||||
* @param filters 过滤条件
|
||||
* @returns 响应数据
|
||||
*/
|
||||
export async function postgrestPut<T, D = Record<string, unknown>>(endpoint: string, data: D): Promise<{data: T; error?: never} | {data?: never; error: string; status?: number}> {
|
||||
export async function postgrestPut<T, D extends object>(
|
||||
endpoint: string,
|
||||
data: D,
|
||||
filters?: Record<string, string>
|
||||
): Promise<{data: T; error?: never} | {data?: never; error: string; status?: number}> {
|
||||
try {
|
||||
// 确保端点没有前导斜杠
|
||||
const apiEndpoint = endpoint.startsWith('/') ? endpoint.substring(1) : endpoint;
|
||||
|
||||
// 构建完整的URL,包含过滤条件
|
||||
let fullEndpoint = apiEndpoint;
|
||||
if (filters) {
|
||||
const filterString = Object.entries(filters)
|
||||
.map(([key, value]) => `${key}=eq.${value}`)
|
||||
.join('&');
|
||||
fullEndpoint = `${apiEndpoint}?${filterString}`;
|
||||
}
|
||||
|
||||
// 打印查询信息(PUT请求只打印端点)
|
||||
logPostgrestQuery(apiEndpoint);
|
||||
logPostgrestQuery(fullEndpoint, undefined, 'PATCH');
|
||||
|
||||
const response = await apiRequest<T>(
|
||||
apiEndpoint,
|
||||
fullEndpoint,
|
||||
{
|
||||
method: 'PATCH',
|
||||
body: JSON.stringify(data),
|
||||
@@ -350,7 +536,11 @@ export async function postgrestPut<T, D = Record<string, unknown>>(endpoint: str
|
||||
throw new Error(response.error);
|
||||
}
|
||||
|
||||
return { data: response.data as T };
|
||||
if (!response.data) {
|
||||
throw new Error('更新成功但未返回数据');
|
||||
}
|
||||
|
||||
return { data: response.data };
|
||||
} catch (error) {
|
||||
const apiError = handleApiError(error);
|
||||
return { error: apiError.message, status: apiError.status };
|
||||
@@ -383,7 +573,7 @@ export async function postgrestDelete<T>(endpoint: string, params?: PostgrestPar
|
||||
}
|
||||
|
||||
// 打印查询信息
|
||||
logPostgrestQuery(apiEndpoint, queryParams);
|
||||
logPostgrestQuery(apiEndpoint, queryParams, 'DELETE');
|
||||
|
||||
const response = await apiRequest<T>(
|
||||
apiEndpoint,
|
||||
|
||||
Reference in New Issue
Block a user