给所有请求都加上jwt,隐藏生成jwt的secret(放到.env中),隐藏app-secret(放在pm2运行配置文件中,后续直接读取环境配置即可)
This commit is contained in:
+98
-30
@@ -1,7 +1,42 @@
|
||||
// app/api/postgrest-client.ts
|
||||
// import { AsyncLocalStorage } from 'async_hooks';
|
||||
import { apiRequest, type QueryParams } from './axios-client';
|
||||
import { handleApiError } from './error-handler';
|
||||
|
||||
/**
|
||||
* 请求上下文接口
|
||||
*/
|
||||
// interface RequestContext {
|
||||
// jwt?: string;
|
||||
// }
|
||||
|
||||
/**
|
||||
* 创建异步本地存储用于存储请求上下文
|
||||
*/
|
||||
// const requestContext = new AsyncLocalStorage<RequestContext>();
|
||||
|
||||
/**
|
||||
* 在指定的上下文中运行函数
|
||||
* @param context 上下文对象
|
||||
* @param fn 要执行的函数
|
||||
* @returns 函数执行结果
|
||||
*/
|
||||
// export function runWithContext<T>(
|
||||
// context: RequestContext,
|
||||
// fn: () => T | Promise<T>
|
||||
// ): T | Promise<T> {
|
||||
// return requestContext.run(context, fn);
|
||||
// }
|
||||
|
||||
/**
|
||||
* 获取当前上下文中的 JWT
|
||||
* @returns JWT token 或 undefined
|
||||
*/
|
||||
// function getContextJWT(): string | undefined {
|
||||
// const context = requestContext.getStore();
|
||||
// return context?.jwt;
|
||||
// }
|
||||
|
||||
/**
|
||||
* PostgresREST 特定的查询参数接口
|
||||
*/
|
||||
@@ -23,6 +58,8 @@ export interface PostgrestParams {
|
||||
[key: string]: unknown;
|
||||
// 自定义头部参数
|
||||
headers?: Record<string, string>;
|
||||
// JWT Token(自动添加到 Authorization 头部)
|
||||
token?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -48,6 +85,38 @@ function decodeUrlForDisplay(url: string): string {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 合并 JWT Token 到请求头
|
||||
* @param existingHeaders 已有的请求头
|
||||
* @param explicitToken 显式传入的 JWT Token(可选)
|
||||
* @returns 合并后的请求头
|
||||
*/
|
||||
function mergeAuthHeaders(
|
||||
existingHeaders: Record<string, string> = {},
|
||||
explicitToken?: string
|
||||
): Record<string, string> {
|
||||
const headers = { ...existingHeaders };
|
||||
|
||||
// 如果已经有 Authorization 头部(不区分大小写),不覆盖
|
||||
const hasAuth = Object.keys(headers).some(
|
||||
key => key.toLowerCase() === 'authorization'
|
||||
);
|
||||
|
||||
if (hasAuth) {
|
||||
return headers;
|
||||
}
|
||||
|
||||
// 优先使用显式传入的 token,否则从上下文获取
|
||||
const token = explicitToken || 'undefined';
|
||||
|
||||
// 如果有 token(显式传入或从上下文获取),添加到 Authorization 头部
|
||||
if (token) {
|
||||
headers['Authorization'] = `Bearer ${token}`;
|
||||
}
|
||||
|
||||
return headers;
|
||||
}
|
||||
|
||||
/**
|
||||
* 打印 PostgREST 查询日志
|
||||
* @param endpoint 端点
|
||||
@@ -167,8 +236,8 @@ export function transformParams(params: PostgrestParams): QueryParams {
|
||||
|
||||
// 处理其他额外参数
|
||||
Object.entries(params).forEach(([key, value]) => {
|
||||
// 跳过已处理的特殊参数
|
||||
if (!['select', 'order', 'limit', 'offset', 'filter', 'schema', 'or'].includes(key) && value !== undefined) {
|
||||
// 跳过已处理的特殊参数(包括 headers 和 token)
|
||||
if (!['select', 'order', 'limit', 'offset', 'filter', 'schema', 'or', 'headers', 'token'].includes(key) && value !== undefined) {
|
||||
result[key] = value as string | number | boolean;
|
||||
}
|
||||
});
|
||||
@@ -179,7 +248,7 @@ export function transformParams(params: PostgrestParams): QueryParams {
|
||||
/**
|
||||
* 发送 GET 请求到 PostgresREST 接口
|
||||
* @param endpoint 端点
|
||||
* @param params 查询参数
|
||||
* @param params 查询参数(可包含 token 和 headers)
|
||||
* @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}> {
|
||||
@@ -191,13 +260,8 @@ export async function postgrestGet<T>(endpoint: string, params?: PostgrestParams
|
||||
// 打印查询信息
|
||||
logPostgrestQuery(apiEndpoint, queryParams, 'GET');
|
||||
|
||||
// 提取并移除自定义头部参数
|
||||
const headers: Record<string, string> = params?.headers || {};
|
||||
|
||||
// 清除查询参数中的headers属性,避免将其作为URL参数
|
||||
if (queryParams.headers) {
|
||||
delete queryParams.headers;
|
||||
}
|
||||
// 合并 JWT Token 到请求头
|
||||
const headers = mergeAuthHeaders(params?.headers, params?.token);
|
||||
|
||||
const response = await apiRequest<T>(
|
||||
apiEndpoint,
|
||||
@@ -215,7 +279,7 @@ export async function postgrestGet<T>(endpoint: string, params?: PostgrestParams
|
||||
// 返回数据和响应头
|
||||
return {
|
||||
data: response.data as T,
|
||||
headers: response.headers // 假设apiRequest函数已返回响应头
|
||||
headers: response.headers
|
||||
};
|
||||
} catch (error) {
|
||||
const apiError = handleApiError(error);
|
||||
@@ -314,9 +378,10 @@ function handlePostgresError(error: unknown, responseText?: string): { message:
|
||||
* 发送 POST 请求到 PostgresREST 接口
|
||||
* @param endpoint 端点(表名)
|
||||
* @param data 请求体数据
|
||||
* @param token JWT Token(可选)
|
||||
* @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}> {
|
||||
export async function postgrestPost<T, D = Record<string, unknown>>(endpoint: string, data: D, token?: string): Promise<{data: T; error?: never} | {data?: never; error: string; status?: number}> {
|
||||
try {
|
||||
// 确保端点没有前导斜杠
|
||||
const apiEndpoint = endpoint.startsWith('/') ? endpoint.substring(1) : endpoint;
|
||||
@@ -332,17 +397,20 @@ export async function postgrestPost<T, D = Record<string, unknown>>(endpoint: st
|
||||
// console.log(`准备发送 PostgreSQL 插入请求到: ${apiEndpoint}`);
|
||||
// console.log(`请求体: ${requestBody}`);
|
||||
|
||||
// 合并 JWT Token 到请求头
|
||||
const headers = mergeAuthHeaders({
|
||||
'Content-Type': 'application/json',
|
||||
'Accept': 'application/json',
|
||||
'Prefer': 'return=representation'
|
||||
}, token);
|
||||
|
||||
try {
|
||||
const response = await apiRequest<T>(
|
||||
apiEndpoint,
|
||||
{
|
||||
method: 'POST',
|
||||
body: requestBody,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Accept': 'application/json',
|
||||
'Prefer': 'return=representation'
|
||||
}
|
||||
headers: headers
|
||||
}
|
||||
);
|
||||
|
||||
@@ -434,12 +502,14 @@ function preprocessData(data: Record<string, unknown>): Record<string, unknown>
|
||||
* @param endpoint 端点
|
||||
* @param data 请求体数据
|
||||
* @param filters 过滤条件
|
||||
* @param token JWT Token(可选)
|
||||
* @returns 响应数据
|
||||
*/
|
||||
export async function postgrestPut<T, D extends object>(
|
||||
endpoint: string,
|
||||
data: D,
|
||||
filters?: Record<string | number, string | number>
|
||||
filters?: Record<string | number, string | number>,
|
||||
token?: string
|
||||
): Promise<{data: T; error?: never} | {data?: never; error: string; status?: number}> {
|
||||
try {
|
||||
// 确保端点没有前导斜杠
|
||||
@@ -459,14 +529,17 @@ export async function postgrestPut<T, D extends object>(
|
||||
// 打印查询信息
|
||||
logPostgrestQuery(fullEndpoint, queryParams, 'PATCH', data as unknown as Record<string, unknown>);
|
||||
|
||||
// 合并 JWT Token 到请求头
|
||||
const headers = mergeAuthHeaders({
|
||||
'Prefer': 'return=representation'
|
||||
}, token);
|
||||
|
||||
const response = await apiRequest<T>(
|
||||
fullEndpoint,
|
||||
{
|
||||
method: 'PATCH',
|
||||
body: JSON.stringify(data),
|
||||
headers: {
|
||||
'Prefer': 'return=representation'
|
||||
}
|
||||
headers: headers
|
||||
},
|
||||
queryParams
|
||||
);
|
||||
@@ -489,7 +562,7 @@ export async function postgrestPut<T, D extends object>(
|
||||
/**
|
||||
* 发送 DELETE 请求到 PostgresREST 接口
|
||||
* @param endpoint 端点
|
||||
* @param params 查询参数,用于指定要删除的记录
|
||||
* @param params 查询参数,用于指定要删除的记录(可包含 token 和 headers)
|
||||
* @returns 响应数据
|
||||
*/
|
||||
export async function postgrestDelete<T>(endpoint: string, params?: PostgrestParams): Promise<{data: T; error?: never} | {data?: never; error: string; status?: number}> {
|
||||
@@ -500,16 +573,11 @@ export async function postgrestDelete<T>(endpoint: string, params?: PostgrestPar
|
||||
// 转换查询参数
|
||||
const queryParams = params ? transformParams(params) : {};
|
||||
|
||||
// 提取并移除自定义头部参数
|
||||
const headers: Record<string, string> = {
|
||||
// 合并 JWT Token 到请求头
|
||||
const headers = mergeAuthHeaders({
|
||||
'Prefer': 'return=representation', // 默认请求返回被删除的记录
|
||||
...(params?.headers || {})
|
||||
};
|
||||
|
||||
// 清除查询参数中的headers属性,避免将其作为URL参数
|
||||
if (queryParams.headers) {
|
||||
delete queryParams.headers;
|
||||
}
|
||||
}, params?.token);
|
||||
|
||||
// 打印查询信息
|
||||
logPostgrestQuery(apiEndpoint, queryParams, 'DELETE');
|
||||
|
||||
Reference in New Issue
Block a user