Files
leaudit-platform-frontend/app/api/postgrest-client.ts
T

508 lines
16 KiB
TypeScript

// app/api/postgrest-client.ts
import { apiRequest, type QueryParams } from './client';
import { handleApiError } from './error-handler';
/**
* PostgresREST 特定的查询参数接口
*/
export interface PostgrestParams {
select?: string;
order?: string;
limit?: number;
offset?: number;
filter?: Record<string, unknown>;
schema?: string; // 指定 PostgreSQL schema
or?: Array<Record<string, unknown>> | string; // 支持OR条件查询
[key: string]: unknown; // 允许添加其他参数
headers?: Record<string, string>;
}
/**
* 将编码后的URL解码为可读格式
* @param url 编码后的URL
* @returns 解码后的可读URL
*/
function decodeUrlForDisplay(url: string): string {
try {
// 首先解码整个URL
const decodedUrl = decodeURIComponent(url);
// 如果URL中包含@符号作为前缀,则移除它
if (decodedUrl.startsWith('@')) {
return decodedUrl.substring(1);
}
return decodedUrl;
} catch (error) {
// 如果解码失败,返回原始URL
console.error('URL解码失败:', error);
return url;
}
}
/**
* 打印 PostgREST 查询日志
* @param endpoint 端点
* @param params 参数
* @param method HTTP 方法
*/
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';
const baseUrl = 'http://nas.7bm.co:3000';
// 确保 endpoint 格式正确
const normalizedEndpoint = endpoint.startsWith('/') ? endpoint.substring(1) : endpoint;
console.log('\n📦 PostgREST 查询日志 ======================start=============');
console.log(`📦 HTTP 方法: ${method}`);
console.log(`📦 API 端点: ${decodeUrlForDisplay(`${baseUrl}/${normalizedEndpoint}`)}`);
if (params && Object.keys(params).length > 0) {
console.log('📦 查询参数:');
// 以可读格式单独打印每个参数
Object.entries(params).forEach(([key, value]) => {
if (value !== undefined) {
console.log(` - ${key}: ${JSON.stringify(value)}`);
}
});
}
console.log('PostgREST 查询日志=============================end============\n');
}
}
/**
* 将通用查询参数转换为 PostgresREST 支持的格式
* @param params 查询参数
* @returns 转换后的 PostgresREST 参数
*/
export function transformParams(params: PostgrestParams): QueryParams {
const result: QueryParams = {};
// 处理 select 参数
if (params.select) {
result.select = params.select;
}
// 处理 order 参数
if (params.order) {
result.order = params.order;
}
// 处理 limit 和 offset 参数
if (params.limit !== undefined) {
result.limit = params.limit;
}
if (params.offset !== undefined) {
result.offset = params.offset;
}
// 处理 schema 参数
if (params.schema) {
result.schema = params.schema;
}
// 处理或条件 (OR) - 两种格式支持
if (params.or) {
// 如果是字符串格式 (例如 "name.ilike.*keyword*,code.ilike.*keyword*")
if (typeof params.or === 'string') {
result.or = params.or;
}
// 如果是数组格式, 转换为 PostgREST 的 or=(condition1,condition2) 格式
else if (Array.isArray(params.or)) {
const orConditions: string[] = [];
params.or.forEach(condition => {
const entries = Object.entries(condition);
if (entries.length === 1) {
const [field, operator] = entries[0];
orConditions.push(`${field}.${operator}`);
}
});
if (orConditions.length > 0) {
result.or = `(${orConditions.join(',')})`;
}
}
}
// 处理过滤条件 - PostgresREST 格式
if (params.filter) {
Object.entries(params.filter).forEach(([key, value]) => {
// 如果值不为 undefined,则添加到查询参数中
if (value !== undefined) {
// 支持 PostgreSQL 的比较操作符 (eq, gt, lt, gte, lte, like, ilike 等)
result[key] = value as string | number | boolean;
}
});
}
// 处理其他额外参数
Object.entries(params).forEach(([key, value]) => {
// 跳过已处理的特殊参数
if (!['select', 'order', 'limit', 'offset', 'filter', 'schema', 'or'].includes(key) && value !== undefined) {
result[key] = value as string | number | boolean;
}
});
return result;
}
/**
* 发送 GET 请求到 PostgresREST 接口
* @param endpoint 端点
* @param params 查询参数
* @returns 响应数据
*/
export async function postgrestGet<T>(endpoint: string, params?: PostgrestParams): Promise<{data: T; headers?: Record<string, string>; error?: never} | {data?: never; error: string; status?: number}> {
try {
const queryParams = params ? transformParams(params) : {};
// 确保端点没有前导斜杠,因为API_BASE_URL已经包含了路径前缀
const apiEndpoint = endpoint.startsWith('/') ? endpoint.substring(1) : endpoint;
// 打印查询信息
logPostgrestQuery(apiEndpoint, queryParams, 'GET');
// 提取并移除自定义头部参数
const headers: Record<string, string> = params?.headers || {};
// 清除查询参数中的headers属性,避免将其作为URL参数
if (queryParams.headers) {
delete queryParams.headers;
}
const response = await apiRequest<T>(
apiEndpoint,
{
method: 'GET',
headers: headers
},
queryParams
);
if (response.error) {
throw new Error(response.error);
}
// 返回数据和响应头
return {
data: response.data as T,
headers: response.headers // 假设apiRequest函数已返回响应头
};
} catch (error) {
const apiError = handleApiError(error);
return { error: apiError.message, status: apiError.status };
}
}
/**
* 处理 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 data 请求体数据
* @returns 响应数据
*/
export async function postgrestPost<T, D = Record<string, unknown>>(endpoint: string, data: D): Promise<{data: T; error?: never} | {data?: never; error: string; status?: number}> {
try {
// 确保端点没有前导斜杠
const apiEndpoint = endpoint.startsWith('/') ? endpoint.substring(1) : endpoint;
// 打印查询信息(POST请求只打印端点)
logPostgrestQuery(apiEndpoint, undefined, 'POST');
// 预处理数据,确保所有字段类型符合 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);
}
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
};
}
} 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 extends object>(
endpoint: string,
data: D,
filters?: Record<string | number, string | number>
): 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(fullEndpoint, undefined, 'PATCH');
const response = await apiRequest<T>(
fullEndpoint,
{
method: 'PATCH',
body: JSON.stringify(data),
headers: {
'Prefer': 'return=representation'
}
}
);
if (response.error) {
throw new Error(response.error);
}
if (!response.data) {
throw new Error('更新成功但未返回数据');
}
return { data: response.data };
} catch (error) {
const apiError = handleApiError(error);
return { error: apiError.message, status: apiError.status };
}
}
/**
* 发送 DELETE 请求到 PostgresREST 接口
* @param endpoint 端点
* @param params 查询参数,用于指定要删除的记录
* @returns 响应数据
*/
export async function postgrestDelete<T>(endpoint: string, params?: PostgrestParams): Promise<{data: T; error?: never} | {data?: never; error: string; status?: number}> {
try {
// 确保端点没有前导斜杠
const apiEndpoint = endpoint.startsWith('/') ? endpoint.substring(1) : endpoint;
// 转换查询参数
const queryParams = params ? transformParams(params) : {};
// 提取并移除自定义头部参数
const headers: Record<string, string> = {
'Prefer': 'return=representation', // 默认请求返回被删除的记录
...(params?.headers || {})
};
// 清除查询参数中的headers属性,避免将其作为URL参数
if (queryParams.headers) {
delete queryParams.headers;
}
// 打印查询信息
logPostgrestQuery(apiEndpoint, queryParams, 'DELETE');
const response = await apiRequest<T>(
apiEndpoint,
{
method: 'DELETE',
headers
},
queryParams
);
if (response.error) {
throw new Error(response.error);
}
return { data: response.data as T };
} catch (error) {
const apiError = handleApiError(error);
return { error: apiError.message, status: apiError.status };
}
}