feat: refine request log
This commit is contained in:
@@ -106,7 +106,15 @@ export const authApi = {
|
|||||||
|
|
||||||
// Logs API
|
// Logs API
|
||||||
export const logsApi = {
|
export const logsApi = {
|
||||||
list: () => request<RequestLog[]>('/logs'),
|
list: (params?: { method?: string; search?: string }) => {
|
||||||
|
const query = new URLSearchParams();
|
||||||
|
if (params?.method) {
|
||||||
|
query.set('method', params.method);
|
||||||
|
}
|
||||||
|
if (params?.search) {
|
||||||
|
query.set('search', params.search);
|
||||||
|
}
|
||||||
|
const queryString = query.toString();
|
||||||
|
return request<RequestLog[]>(`/logs${queryString ? `?${queryString}` : ''}`);
|
||||||
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
export const fetchLogs = logsApi.list;
|
|
||||||
|
|||||||
@@ -64,7 +64,7 @@ const ChangePassword: Component<ChangePasswordProps> = (props) => {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<Modal>
|
<Modal>
|
||||||
<ModalContent>
|
<ModalContent class="max-w-md">
|
||||||
<CardHeader>
|
<CardHeader>
|
||||||
<h3 class="text-lg font-medium text-gray-900">Change Password</h3>
|
<h3 class="text-lg font-medium text-gray-900">Change Password</h3>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
|
|||||||
@@ -1,47 +1,103 @@
|
|||||||
import { Component, createSignal, For } from 'solid-js';
|
import { Component, createSignal, For, Show } from 'solid-js';
|
||||||
import type { RequestLog } from '../types';
|
import type { RequestLog } from '../types';
|
||||||
import { Card } from './ui/Card';
|
import { Button } from './ui/Button';
|
||||||
|
import { CardContent, CardFooter, CardHeader } from './ui/Card';
|
||||||
|
import { Modal, ModalContent } from './ui/Modal';
|
||||||
|
|
||||||
const TreeView: Component<{ data: any; name: string }> = (props) => {
|
interface TreeViewProps {
|
||||||
const [isOpen, setIsOpen] = createSignal(true);
|
data: any;
|
||||||
|
name: string;
|
||||||
|
isRoot?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
const TreeView: Component<TreeViewProps> = (props) => {
|
||||||
|
const [isOpen, setIsOpen] = createSignal(props.isRoot ?? false);
|
||||||
const isObject = typeof props.data === 'object' && props.data !== null;
|
const isObject = typeof props.data === 'object' && props.data !== null;
|
||||||
|
|
||||||
|
const renderValue = (value: any) => {
|
||||||
|
switch (typeof value) {
|
||||||
|
case 'string':
|
||||||
|
return <span class="text-green-600">"{value}"</span>;
|
||||||
|
case 'number':
|
||||||
|
return <span class="text-blue-600">{value}</span>;
|
||||||
|
case 'boolean':
|
||||||
|
return <span class="text-purple-600">{String(value)}</span>;
|
||||||
|
case 'object':
|
||||||
|
if (value === null) return <span class="text-gray-500">null</span>;
|
||||||
|
// This case is handled by recursive TreeView
|
||||||
|
default:
|
||||||
|
return <span class="text-gray-500">{String(value)}</span>;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div class="ml-4 my-1">
|
<div class="font-mono text-sm">
|
||||||
<div class="flex items-center">
|
<div
|
||||||
<span class="cursor-pointer" onClick={() => setIsOpen(!isOpen())}>
|
class="flex items-center cursor-pointer hover:bg-gray-100 rounded px-1"
|
||||||
|
onClick={() => setIsOpen(!isOpen())}
|
||||||
|
>
|
||||||
|
<span class="w-4 inline-block text-gray-500">
|
||||||
{isObject ? (isOpen() ? '▼' : '►') : ''}
|
{isObject ? (isOpen() ? '▼' : '►') : ''}
|
||||||
</span>
|
</span>
|
||||||
<span class="font-semibold ml-2">{props.name}</span>
|
<span class="font-semibold text-gray-800">{props.name}:</span>
|
||||||
|
<Show when={!isObject}>
|
||||||
|
<span class="ml-2">{renderValue(props.data)}</span>
|
||||||
|
</Show>
|
||||||
</div>
|
</div>
|
||||||
{isOpen() && isObject && (
|
<Show when={isOpen() && isObject}>
|
||||||
<div class="pl-4 border-l-2 border-gray-200">
|
<div class="pl-4 border-l border-gray-200 ml-3">
|
||||||
<For each={Object.entries(props.data)}>
|
<For each={Object.entries(props.data)}>
|
||||||
{([key, value]) => {
|
{([key, value]) => <TreeView name={key} data={value} />}
|
||||||
if (typeof value === 'object' && value !== null && 'modified' in value && 'value' in value) {
|
|
||||||
return <TreeView name={key} data={value.value} />
|
|
||||||
}
|
|
||||||
return <TreeView name={key} data={value} />
|
|
||||||
}}
|
|
||||||
</For>
|
</For>
|
||||||
</div>
|
</div>
|
||||||
)}
|
</Show>
|
||||||
{isOpen() && !isObject && <div class="pl-6 text-gray-700">{JSON.stringify(props.data)}</div>}
|
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
const RequestDetails: Component<{ log: RequestLog }> = (props) => {
|
interface RequestDetailsProps {
|
||||||
|
log: RequestLog;
|
||||||
|
onClose: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
const RequestDetails: Component<RequestDetailsProps> = (props) => {
|
||||||
return (
|
return (
|
||||||
<Card class="p-4">
|
<Modal>
|
||||||
<h2 class="text-xl font-bold mb-4">Request Details</h2>
|
<ModalContent class="max-w-3xl h-auto max-h-[90vh]">
|
||||||
{/* TODO: interception method */}
|
<CardHeader>
|
||||||
<div>
|
<h3 class="text-lg font-medium text-gray-900">Request Details</h3>
|
||||||
<TreeView name="Request" data={props.log.request_body} />
|
<p class="text-sm text-gray-500">{props.log.method} at {new Date(props.log.created_at).toLocaleString()}</p>
|
||||||
<TreeView name="Response" data={props.log.response_body} />
|
</CardHeader>
|
||||||
</div>
|
|
||||||
</Card>
|
<CardContent class="max-h-[70vh] overflow-y-auto">
|
||||||
|
<div class="grid grid-cols-1 gap-4">
|
||||||
|
<div>
|
||||||
|
<h4 class="font-semibold mb-2">Request</h4>
|
||||||
|
<div class="bg-gray-50 p-3 rounded overflow-x-auto">
|
||||||
|
<TreeView name="body" data={props.log.request_body} isRoot={true} />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<h4 class="font-semibold mb-2">Response</h4>
|
||||||
|
<div class="bg-gray-50 p-3 rounded overflow-x-auto">
|
||||||
|
<TreeView name="body" data={props.log.response_body} isRoot={true} />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
|
||||||
|
<CardFooter class="flex justify-end pt-4">
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="secondary"
|
||||||
|
onClick={props.onClose}
|
||||||
|
>
|
||||||
|
Close
|
||||||
|
</Button>
|
||||||
|
</CardFooter>
|
||||||
|
</ModalContent>
|
||||||
|
</Modal>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -1,57 +1,111 @@
|
|||||||
import { Component, createSignal, onMount, For, Show } from 'solid-js';
|
import { Component, createMemo, createResource, createSignal, For, Show } from 'solid-js';
|
||||||
import { fetchLogs } from '../api/client';
|
import { logsApi } from '../api/client';
|
||||||
import type { RequestLog as RequestLogType } from '../types';
|
import type { RequestLog as RequestLogType } from '../types';
|
||||||
import RequestDetails from './RequestDetails';
|
|
||||||
import { Card } from './ui/Card';
|
import { Card } from './ui/Card';
|
||||||
|
import { Input } from './ui/Input';
|
||||||
|
import { Select } from './ui/Select';
|
||||||
|
import RequestDetails from './RequestDetails';
|
||||||
|
|
||||||
const RequestLog: Component = () => {
|
const RequestLog: Component = () => {
|
||||||
const [logs, setLogs] = createSignal<RequestLogType[]>([]);
|
const [search, setSearch] = createSignal('');
|
||||||
|
const [method, setMethod] = createSignal('');
|
||||||
const [selectedLog, setSelectedLog] = createSignal<RequestLogType | null>(null);
|
const [selectedLog, setSelectedLog] = createSignal<RequestLogType | null>(null);
|
||||||
|
|
||||||
onMount(async () => {
|
const [logs] = createResource(
|
||||||
try {
|
() => ({ search: search(), method: method() }),
|
||||||
const fetchedLogs = await fetchLogs();
|
async (filters) => {
|
||||||
setLogs(fetchedLogs);
|
// Solid's createResource refetches when the source accessor changes.
|
||||||
} catch (error) {
|
// We can add a debounce here if we want to avoid too many requests.
|
||||||
console.error('Error fetching logs:', error);
|
return logsApi.list(filters);
|
||||||
}
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
const methods = createMemo(() => {
|
||||||
|
if (!logs()) return [];
|
||||||
|
const allMethods = logs()!.map(log => log.method);
|
||||||
|
return [...new Set(allMethods)];
|
||||||
});
|
});
|
||||||
|
|
||||||
const handleLogClick = (log: RequestLogType) => {
|
const handleLogClick = (log: RequestLogType) => {
|
||||||
setSelectedLog(log);
|
setSelectedLog(log);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const handleCloseDetails = () => {
|
||||||
|
setSelectedLog(null);
|
||||||
|
};
|
||||||
|
|
||||||
|
const formatDate = (dateStr: string) => {
|
||||||
|
return new Date(dateStr).toLocaleString();
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div class="flex space-x-4">
|
<>
|
||||||
<div class={selectedLog() ? "w-1/3" : "w-full"}>
|
<div class="space-y-4">
|
||||||
<h2 class="text-2xl font-semibold">Request Log</h2>
|
<h2 class="text-2xl font-semibold">Request Log</h2>
|
||||||
<div class="overflow-x-auto">
|
|
||||||
<Card>
|
<Card>
|
||||||
<ul class="divide-y divide-gray-200">
|
<div class="p-4 flex items-center space-x-4 bg-gray-50 border-b">
|
||||||
<For each={logs()}>
|
<div class="flex-1">
|
||||||
{(log) => (
|
<Input
|
||||||
<li
|
type="text"
|
||||||
class="p-4 hover:bg-gray-50 cursor-pointer"
|
placeholder="Search in request/response..."
|
||||||
onClick={() => handleLogClick(log)}
|
value={search()}
|
||||||
>
|
onInput={(e) => setSearch(e.currentTarget.value)}
|
||||||
<div class="flex justify-between">
|
/>
|
||||||
<span class="font-medium">{log.method}</span>
|
</div>
|
||||||
<span class="text-sm text-gray-500">{new Date(log.created_at).toLocaleTimeString()}</span>
|
<div>
|
||||||
</div>
|
<Select
|
||||||
</li>
|
value={method()}
|
||||||
)}
|
onChange={(e) => setMethod(e.currentTarget.value)}
|
||||||
</For>
|
class="min-w-[200px]"
|
||||||
</ul>
|
>
|
||||||
</Card>
|
<option value="">All Methods</option>
|
||||||
</div>
|
<For each={methods()}>
|
||||||
|
{(m) => <option value={m}>{m}</option>}
|
||||||
|
</For>
|
||||||
|
</Select>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="overflow-x-auto">
|
||||||
|
<table class="min-w-full divide-y divide-gray-200">
|
||||||
|
<thead class="bg-gray-50">
|
||||||
|
<tr>
|
||||||
|
<th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Method</th>
|
||||||
|
<th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Time</th>
|
||||||
|
<th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Request Body</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody class="bg-white divide-y divide-gray-200">
|
||||||
|
<Show when={!logs.loading} fallback={<tr><td colspan="3" class="text-center py-4">Loading...</td></tr>}>
|
||||||
|
<For each={logs()} fallback={
|
||||||
|
<tr>
|
||||||
|
<td colspan="3" class="text-center py-8 text-gray-500">
|
||||||
|
No logs found.
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
}>
|
||||||
|
{(log) => (
|
||||||
|
<tr class="hover:bg-gray-50 cursor-pointer" onClick={() => handleLogClick(log)}>
|
||||||
|
<td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">{log.method}</td>
|
||||||
|
<td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{formatDate(log.created_at)}</td>
|
||||||
|
<td class="px-6 py-4 text-sm text-gray-500 font-mono truncate max-w-lg">
|
||||||
|
{JSON.stringify(log.request_body)}
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
)}
|
||||||
|
</For>
|
||||||
|
</Show>
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</Card>
|
||||||
</div>
|
</div>
|
||||||
<Show when={selectedLog()}>
|
<Show when={selectedLog()}>
|
||||||
{(log) =>
|
{(log) => <RequestDetails log={log()} onClose={handleCloseDetails} />}
|
||||||
<div class="w-2/3">
|
|
||||||
<RequestDetails log={log()} />
|
|
||||||
</div>}
|
|
||||||
</Show>
|
</Show>
|
||||||
</div>
|
</>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -4,20 +4,20 @@ const Modal: Component<JSX.HTMLAttributes<HTMLDivElement>> = (props) => {
|
|||||||
const [local, others] = splitProps(props, ['class']);
|
const [local, others] = splitProps(props, ['class']);
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
class={`fixed inset-0 bg-gray-500 bg-opacity-75 flex items-center justify-center z-50 ${local.class}`}
|
class={`fixed inset-0 bg-gray-500 bg-opacity-75 flex items-center justify-center z-50 ${local.class || ""}`}
|
||||||
{...others}
|
{...others}
|
||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
const ModalContent: Component<JSX.HTMLAttributes<HTMLDivElement>> = (props) => {
|
const ModalContent: Component<JSX.HTMLAttributes<HTMLDivElement>> = (props) => {
|
||||||
const [local, others] = splitProps(props, ['class']);
|
const [local, others] = splitProps(props, ['class']);
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
class={`bg-white rounded-lg shadow-xl max-w-md w-full mx-4 ${local.class}`}
|
class={`bg-white rounded-lg shadow-xl w-full mx-4 ${local.class || ""}`}
|
||||||
{...others}
|
{...others}
|
||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
export { Modal, ModalContent };
|
export { Modal, ModalContent };
|
||||||
|
|||||||
@@ -1,15 +1,17 @@
|
|||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
|
||||||
use axum::{
|
use axum::{
|
||||||
Json,
|
extract::{Path, Query, State},
|
||||||
extract::{Path, State},
|
|
||||||
http::StatusCode,
|
http::StatusCode,
|
||||||
|
Json,
|
||||||
};
|
};
|
||||||
|
use serde::Deserialize;
|
||||||
use tracing::error;
|
use tracing::error;
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
AppContext, auth,
|
auth,
|
||||||
db::{self, models::RequestLog},
|
db::{self, models::RequestLog},
|
||||||
|
AppContext,
|
||||||
};
|
};
|
||||||
|
|
||||||
use super::models::*;
|
use super::models::*;
|
||||||
@@ -237,7 +239,10 @@ pub async fn update_rule(
|
|||||||
{
|
{
|
||||||
Ok(_) => match db::repositories::rules::find_by_id(&state.db, id).await {
|
Ok(_) => match db::repositories::rules::find_by_id(&state.db, id).await {
|
||||||
Ok(Some(rule)) => Ok(Json(rule.into())),
|
Ok(Some(rule)) => Ok(Json(rule.into())),
|
||||||
_ => Err((StatusCode::NOT_FOUND, Json(ApiError::new("Rule not found")))),
|
_ => Err((
|
||||||
|
StatusCode::NOT_FOUND,
|
||||||
|
Json(ApiError::new("Rule not found")),
|
||||||
|
)),
|
||||||
},
|
},
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
error!("Failed to update rule: {}", e);
|
error!("Failed to update rule: {}", e);
|
||||||
@@ -310,11 +315,25 @@ pub async fn verify_command(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Log handlers
|
// Log handlers
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
pub struct ListLogsParams {
|
||||||
|
pub method: Option<String>,
|
||||||
|
pub search: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
pub async fn list_logs(
|
pub async fn list_logs(
|
||||||
State(state): State<Arc<AppContext>>,
|
State(state): State<Arc<AppContext>>,
|
||||||
|
Query(params): Query<ListLogsParams>,
|
||||||
) -> Result<Json<Vec<RequestLog>>, (StatusCode, Json<ApiError>)> {
|
) -> Result<Json<Vec<RequestLog>>, (StatusCode, Json<ApiError>)> {
|
||||||
match db::repositories::logs::list_all(&state.db).await {
|
match db::repositories::logs::list(
|
||||||
|
&state.db,
|
||||||
|
params.method.as_deref(),
|
||||||
|
params.search.as_deref(),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
{
|
||||||
Ok(logs) => Ok(Json(logs)),
|
Ok(logs) => Ok(Json(logs)),
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
error!("Failed to list logs: {}", e);
|
error!("Failed to list logs: {}", e);
|
||||||
|
|||||||
@@ -1,13 +1,37 @@
|
|||||||
use crate::db::models::RequestLog;
|
use crate::db::models::RequestLog;
|
||||||
use serde_json::Value;
|
use serde_json::Value;
|
||||||
use sqlx::SqlitePool;
|
use sqlx::{QueryBuilder, SqlitePool};
|
||||||
|
|
||||||
pub async fn list_all(pool: &SqlitePool) -> anyhow::Result<Vec<RequestLog>> {
|
pub async fn list(
|
||||||
Ok(
|
pool: &SqlitePool,
|
||||||
sqlx::query_as::<_, RequestLog>("SELECT * FROM request_logs ORDER BY created_at")
|
method: Option<&str>,
|
||||||
.fetch_all(pool)
|
search: Option<&str>,
|
||||||
.await?,
|
) -> anyhow::Result<Vec<RequestLog>> {
|
||||||
)
|
let mut builder: QueryBuilder<sqlx::Sqlite> =
|
||||||
|
QueryBuilder::new("SELECT * FROM request_logs");
|
||||||
|
|
||||||
|
if let Some(method_val) = method {
|
||||||
|
builder.push(" WHERE method = ");
|
||||||
|
builder.push_bind(method_val);
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some(search_val) = search {
|
||||||
|
let pattern = format!("%{}%", search_val);
|
||||||
|
if method.is_some() {
|
||||||
|
builder.push(" AND (request_body LIKE ");
|
||||||
|
} else {
|
||||||
|
builder.push(" WHERE (request_body LIKE ");
|
||||||
|
}
|
||||||
|
builder.push_bind(pattern.clone());
|
||||||
|
builder.push(" OR response_body LIKE ");
|
||||||
|
builder.push_bind(pattern);
|
||||||
|
builder.push(")");
|
||||||
|
}
|
||||||
|
|
||||||
|
builder.push(" ORDER BY created_at DESC");
|
||||||
|
|
||||||
|
let query = builder.build_query_as();
|
||||||
|
Ok(query.fetch_all(pool).await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn create(
|
pub async fn create(
|
||||||
|
|||||||
Reference in New Issue
Block a user