Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions internal/core/hook_core.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ type TokenGenerator func() string
type HookRepository interface {
CreateHook(ctx context.Context, token string) (domain.Hook, error)
GetHookByToken(ctx context.Context, token string) (domain.Hook, error)
ListHooks(ctx context.Context) ([]domain.Hook, error)
CreateWebhookRequest(ctx context.Context, params domain.CreateWebhookRequestParams) (domain.WebhookRequest, error)
ListWebhookRequests(ctx context.Context, hookID int64) ([]domain.WebhookRequest, error)
GetHookResponse(ctx context.Context, hookID int64) (domain.HookResponse, error)
Expand All @@ -36,6 +37,10 @@ func NewHook(repo HookRepository, generateToken TokenGenerator) *Hook {
}
}

func (s *Hook) ListHooks(ctx context.Context) ([]domain.Hook, error) {
return s.repo.ListHooks(ctx)
}

func (s *Hook) CreateHook(ctx context.Context, token string) (domain.Hook, error) {
if token == "" {
token = s.generateToken()
Expand Down
14 changes: 14 additions & 0 deletions internal/repos/hook.go
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,20 @@ func (r *Hook) ListWebhookRequests(ctx context.Context, hookID int64) ([]domain.
return result, nil
}

func (r *Hook) ListHooks(ctx context.Context) ([]domain.Hook, error) {
rows, err := r.q.ListHooks(ctx)
if err != nil {
return nil, err
}

result := make([]domain.Hook, len(rows))
for i, row := range rows {
result[i] = toDomainHook(row)
}

return result, nil
}

func (r *Hook) GetHookResponse(ctx context.Context, hookID int64) (domain.HookResponse, error) {
row, err := r.q.GetHookResponseByHookID(ctx, hookID)
if err != nil {
Expand Down
8 changes: 8 additions & 0 deletions internal/server/contract.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,14 @@ type CreateEndpointResponseContract struct {
URL string `json:"url"`
}

type EndpointListItemContract struct {
ID int64 `json:"id"`
Token string `json:"token"`
Name string `json:"name,omitempty"`
URL string `json:"url"`
CreatedAt time.Time `json:"createdAt"`
}

type WebhookRequestContract struct {
ID int64 `json:"id"`
HookID int64 `json:"hookId"`
Expand Down
31 changes: 31 additions & 0 deletions internal/server/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import (
const DefaultMaxBodySize int64 = 5 << 20 // 5MB

type HookService interface {
ListHooks(ctx context.Context) ([]domain.Hook, error)
CreateHook(ctx context.Context, token string) (domain.Hook, error)
ReceiveWebhook(ctx context.Context, token string, params domain.CreateWebhookRequestParams) (domain.WebhookRequest, domain.HookResponse, error)
ListWebhookRequests(ctx context.Context, token string) ([]domain.WebhookRequest, error)
Expand Down Expand Up @@ -54,6 +55,7 @@ func NewHook(deps *HookDeps) *Hook {
}

func (h *Hook) RegisterRoutes() {
h.deps.Mux.HandleFunc("GET /api/endpoints", h.ListEndpoints)
h.deps.Mux.HandleFunc("POST /api/endpoints", h.CreateEndpoint)
h.deps.Mux.HandleFunc("GET /api/endpoints/{token}/requests", h.ListRequests)
h.deps.Mux.HandleFunc("GET /api/endpoints/{token}/events", h.StreamEvents)
Expand All @@ -62,6 +64,35 @@ func (h *Hook) RegisterRoutes() {
h.deps.Mux.HandleFunc("/r/{token}", h.ReceiveWebhook)
}

func (h *Hook) ListEndpoints(w http.ResponseWriter, r *http.Request) {
hooks, err := h.deps.Service.ListHooks(r.Context())
if err != nil {
slog.Error("list endpoints", "err", err)
SendError(w, http.StatusInternalServerError, ErrInternal)
return
}

contracts := make([]EndpointListItemContract, len(hooks))
for i, hook := range hooks {
contracts[i] = EndpointListItemContract{
ID: hook.ID,
Token: hook.Token,
Name: hook.Name,
URL: h.deps.Opts.BaseURL + "/r/" + hook.Token,
CreatedAt: hook.CreatedAt,
}
}

data, err := json.Marshal(contracts)
if err != nil {
slog.Error("marshal endpoints", "err", err)
SendError(w, http.StatusInternalServerError, ErrInternal)
return
}

SendSuccess(w, http.StatusOK, data)
}

func (h *Hook) CreateEndpoint(w http.ResponseWriter, r *http.Request) {
if h.readOnly(w) {
return
Expand Down
5 changes: 5 additions & 0 deletions internal/store/query/hooks.sql
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,11 @@ ON CONFLICT (hook_id) DO UPDATE SET
updated_at = CURRENT_TIMESTAMP
RETURNING id, hook_id, status_code, headers, body, created_at, updated_at;

-- name: ListHooks :many
SELECT id, token, name, created_at, updated_at
FROM hooks
ORDER BY created_at DESC;

-- name: GetHookResponseByHookID :one
SELECT id, hook_id, status_code, headers, body, created_at, updated_at
FROM hook_responses
Expand Down
34 changes: 34 additions & 0 deletions internal/store/sqlc/hooks.sql.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

9 changes: 2 additions & 7 deletions internal/web/ui/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -82,14 +82,9 @@ <h2>Welcome to Webhix</h2>
<aside class="endpoints-panel">
<div class="panel-header">
<h3>Endpoints</h3>
<span class="count-badge">1</span>
<span class="count-badge" id="endpointsPanelCount">0</span>
</div>
<button class="endpoint-card active">
<span class="method-badge method-POST">POST</span>
<strong id="endpointName">active-endpoint</strong>
<small id="endpointPath">/r/current-token</small>
<span class="endpoint-count">Live</span>
</button>
<div id="endpointsList"></div>
</aside>

<div class="detail-panel" id="detailPanel">
Expand Down
41 changes: 39 additions & 2 deletions internal/web/ui/src/app/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,10 @@ import './styles.css';
import {
connectEvents,
createEndpoint,
fetchEndpoints,
fetchRequests,
} from '../features/endpoint-session/api/endpoint-api';
import type { Endpoint } from '../features/endpoint-session/api/endpoint-api';
import { getElements } from './dom';
import { renderRequestList, refreshRelativeTimes } from '../widgets/request-list/request-list';
import { renderSelectedDetail, showPlaceholder } from '../widgets/request-detail/request-detail';
Expand All @@ -26,6 +28,7 @@ const state = createInitialState();
const elements = getElements();
let eventSource: EventSource | null = null;
let toastTimer: ReturnType<typeof setTimeout> | undefined;
let currentToken: string | null = null;

init();

Expand Down Expand Up @@ -82,26 +85,60 @@ function loadToken(): void {
}

function activateToken(token: string): void {
currentToken = token;
resetForToken(state, token);

const url = new URL(location.href);
url.searchParams.set('token', token);
history.replaceState(null, '', url.toString());

elements.pillURL.textContent = `${location.origin}/r/${token}`;
document.getElementById('endpointName')?.replaceChildren(document.createTextNode(token));
document.getElementById('endpointTitle')?.replaceChildren(document.createTextNode(token));
document.getElementById('endpointPath')?.replaceChildren(document.createTextNode(`/r/${token}`));
elements.pillArea.classList.remove('hidden');
elements.overlay.classList.add('hidden');
elements.mainArea.classList.remove('hidden');

renderRequestList(elements, state);
showPlaceholder(elements);
void loadHistory(token);
void loadEndpoints();
connectSSE(token);
}

async function loadEndpoints(): Promise<void> {
try {
const eps = await fetchEndpoints();
renderEndpointsList(eps);
} catch {
// silently fail
}
}

function renderEndpointsList(endpoints: Endpoint[]): void {
const list = document.getElementById('endpointsList');
const countBadge = document.getElementById('endpointsPanelCount');
if (!list) return;

if (countBadge) countBadge.textContent = String(endpoints.length);

list.innerHTML = '';
for (const ep of endpoints) {
const btn = document.createElement('button');
btn.className = 'endpoint-card' + (ep.token === currentToken ? ' active' : '');
btn.dataset.token = ep.token;

const label = document.createElement('strong');
label.textContent = ep.name || ep.token;

const path = document.createElement('small');
path.textContent = `/r/${ep.token}`;

btn.append(label, path);
btn.addEventListener('click', () => activateToken(ep.token));
list.appendChild(btn);
}
}

async function createNewEndpoint(): Promise<void> {
try {
const token = await createEndpoint();
Expand Down
15 changes: 15 additions & 0 deletions internal/web/ui/src/features/endpoint-session/api/endpoint-api.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,20 @@
import type { ApiResponse, WebhookRequest } from '../../../entities/request/model/types';

export interface Endpoint {
id: number;
token: string;
name?: string;
url: string;
createdAt: string;
}

export async function fetchEndpoints(): Promise<Endpoint[]> {
const response = await fetch('/api/endpoints');
const json = (await response.json()) as ApiResponse<Endpoint[]>;
if (!json.success) return [];
return json.body ?? [];
}

export async function createEndpoint(): Promise<string> {
const response = await fetch('/api/endpoints', {
method: 'POST',
Expand Down