refactor: migrate all page.server.ts files to typed API client

All server-side fetch calls now go through createApiClient() from
$lib/api.server.ts, which wraps openapi-fetch with the generated OpenAPI
types. This means backend changes are reflected in the frontend after
running npm run generate:api.

- Add stub src/lib/generated/api.ts (replaced by generate:api output)
- Fix GroupController: missing /api prefix and ResponseStatusException
- Root, conversations, persons, documents pages all use typed client
- Error handling uses apiError.code directly (no parseBackendError needed)
- Edit page load uses typed client; PUT action keeps raw fetch (multipart)
- Login keeps raw fetch (explicit Authorization header, not cookie auth)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
Marcel
2026-03-15 13:39:15 +01:00
parent 5d356cd694
commit d76248cffd
11 changed files with 220 additions and 259 deletions

View File

@@ -9,7 +9,8 @@ import org.raddatz.familienarchiv.repository.UserGroupRepository;
import org.raddatz.familienarchiv.security.Permission;
import org.raddatz.familienarchiv.security.RequirePermission;
import org.raddatz.familienarchiv.service.UserService;
import org.springframework.http.HttpStatus;
import org.raddatz.familienarchiv.exception.DomainException;
import org.raddatz.familienarchiv.exception.ErrorCode;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
@@ -19,12 +20,11 @@ import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ResponseStatusException;
import lombok.RequiredArgsConstructor;
@RestController
@RequestMapping("/groups")
@RequestMapping("/api/groups")
@RequirePermission(Permission.ADMIN_PERMISSION)
@RequiredArgsConstructor
public class GroupController {
@@ -42,7 +42,7 @@ public class GroupController {
@PatchMapping("/{id}")
public ResponseEntity<UserGroup> updateGroup(@PathVariable UUID id, @RequestBody GroupDTO dto) {
UserGroup group = groupRepository.findById(id)
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND));
.orElseThrow(() -> DomainException.notFound(ErrorCode.INTERNAL_ERROR, "Group not found: " + id));
if (dto.getName() != null)
group.setName(dto.getName());
@@ -53,14 +53,9 @@ public class GroupController {
}
@DeleteMapping("/{id}")
public ResponseEntity<?> deleteGroup(@PathVariable UUID id) {
try {
// Optional: Check if users are assigned before deleting
groupRepository.deleteById(id);
return ResponseEntity.ok().build();
} catch (Exception e) {
return ResponseEntity.badRequest().body("Gruppe konnte nicht gelöscht werden.");
}
public ResponseEntity<Void> deleteGroup(@PathVariable UUID id) {
groupRepository.deleteById(id);
return ResponseEntity.ok().build();
}
@GetMapping("")

3
frontend/.gitignore vendored
View File

@@ -26,4 +26,5 @@ vite.config.ts.timestamp-*
src/lib/paraglide
# Generated OpenAPI types — regenerate with: npm run generate:api
src/lib/generated/api.ts
# (committed as a stub; overwritten by the real spec after generation)
# src/lib/generated/api.ts

View File

@@ -0,0 +1,15 @@
/**
* STUB — generated by openapi-typescript
*
* Run `npm run generate:api` with the backend running in dev mode to
* replace this file with fully-typed definitions.
*
* While this stub is in place the typed client still works; TypeScript
* will start enforcing path and parameter correctness once the real
* types are generated.
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export type paths = Record<string, any>;
export type components = Record<string, never>;
export type operations = Record<string, never>;

View File

@@ -1,72 +1,58 @@
import { redirect } from '@sveltejs/kit';
import type { PageServerLoad } from './$types';
import { createApiClient } from '$lib/api.server';
export const load: PageServerLoad = async ({ url, fetch }) => {
// 1. Extract params
export async function load({ url, fetch }) {
const q = url.searchParams.get('q') || '';
const from = url.searchParams.get('from') || '';
const to = url.searchParams.get('to') || '';
const senderId = url.searchParams.get('senderId') || '';
const receiverId = url.searchParams.get('receiverId') || '';
const tags = url.searchParams.getAll('tag') || '';
const tags = url.searchParams.getAll('tag');
// 2. Build Search URL
const searchUrl = new URL('http://localhost:8080/api/documents/search');
if (q) searchUrl.searchParams.set('q', q);
if (from) searchUrl.searchParams.set('from', from);
if (to) searchUrl.searchParams.set('to', to);
if (senderId) searchUrl.searchParams.set('senderId', senderId);
if (receiverId) searchUrl.searchParams.set('receiverId', receiverId);
if(tags) tags.forEach(tag => searchUrl.searchParams.append('tag', tag));
// 3. Build Persons URL (to resolve names for the typeahead initial value)
// Ideally, we would have endpoints like /api/persons/{id}, but for now we load the list or search.
// To keep it simple and performant enough for now, we fetch all to find the names.
const personsUrl = 'http://localhost:8080/api/persons';
const api = createApiClient(fetch);
try {
const [docsRes, personsRes] = await Promise.all([
fetch(searchUrl.toString()),
fetch(personsUrl)
const [docsResult, personsResult] = await Promise.all([
api.GET('/api/documents/search', {
params: {
query: {
q: q || undefined,
from: from || undefined,
to: to || undefined,
senderId: senderId || undefined,
receiverId: receiverId || undefined,
tag: tags.length ? tags : undefined
}
}
}),
api.GET('/api/persons')
]);
if (docsRes.status === 401 || personsRes.status === 401) {
if (docsResult.response.status === 401 || personsResult.response.status === 401) {
throw redirect(302, '/login');
}
const documents = await docsRes.json();
const allPersons = await personsRes.json();
const documents = docsResult.data ?? [];
const allPersons: { id: string; firstName: string; lastName: string }[] = personsResult.data ?? [];
// Resolve Names for the Typeahead Inputs
const senderObj = allPersons.find((p: any) => p.id === senderId);
const receiverObj = allPersons.find((p: any) => p.id === receiverId);
const senderName = senderObj ? `${senderObj.firstName} ${senderObj.lastName}` : '';
const receiverName = receiverObj ? `${receiverObj.firstName} ${receiverObj.lastName}` : '';
const senderObj = allPersons.find(p => p.id === senderId);
const receiverObj = allPersons.find(p => p.id === receiverId);
return {
documents,
// We don't need to pass the full persons list to the frontend anymore,
// as the Typeahead fetches it dynamically. We only pass the resolved names.
initialValues: {
senderName,
receiverName
senderName: senderObj ? `${senderObj.firstName} ${senderObj.lastName}` : '',
receiverName: receiverObj ? `${receiverObj.firstName} ${receiverObj.lastName}` : ''
},
filters: { q, from, to, senderId, receiverId, tags }
};
} catch (error) {
console.error("Error loading data:", error);
} catch (e) {
if ((e as { status?: number }).status) throw e;
console.error('Error loading data:', e);
return {
documents: [],
initialValues: { senderName: '', receiverName: '' },
filters: { q, from, to, senderId, receiverId },
error: "Could not load data."
filters: { q, from, to, senderId, receiverId, tags }
};
}
};
}

View File

@@ -1,159 +1,146 @@
import { error, fail } from '@sveltejs/kit';
import { env } from '$env/dynamic/private';
import { parseBackendError, getErrorMessage } from '$lib/errors';
import { createApiClient } from '$lib/api.server';
import { getErrorMessage } from '$lib/errors';
export async function load({ fetch, locals }) {
// 1. Check Permissions (Adapt logic to your user object)
const user = locals.user;
// Assuming user.group.permissions is an array of strings
const hasAdmin = user?.groups.some(g => g.permissions.includes("ADMIN"));
const hasAdmin = user?.groups.some((g: { permissions: string[] }) => g.permissions.includes('ADMIN'));
if (!hasAdmin) throw error(403, getErrorMessage('FORBIDDEN'));
const baseUrl = env.API_INTERNAL_URL || 'http://localhost:8080';
const api = createApiClient(fetch);
// 2. Load Data
const [usersRes, groupsRes, tagsRes] = await Promise.all([
fetch(baseUrl + '/api/users'),
fetch(baseUrl + '/api/groups'),
fetch(baseUrl + '/api/tags')
const [usersResult, groupsResult, tagsResult] = await Promise.all([
api.GET('/api/users'),
api.GET('/api/groups'),
api.GET('/api/tags')
]);
return {
users: await usersRes.json(),
groups: await groupsRes.json(),
tags: await tagsRes.json()
};
return {
users: usersResult.data ?? [],
groups: groupsResult.data ?? [],
tags: tagsResult.data ?? []
};
}
export const actions = {
createUser: async ({ request, fetch }) => {
const data = await request.formData();
const baseUrl = env.API_INTERNAL_URL || 'http://localhost:8080';
const api = createApiClient(fetch);
// Extract array of group IDs
// "groupIds" matches the name attribute in the <select>
const groupIds = data.getAll('groupIds');
const payload = {
username: data.get('username'),
initialPassword: data.get('password'),
groupIds: groupIds // Send array to backend
};
console.log("Payload", JSON.stringify(payload))
const res = await fetch(baseUrl + '/api/users', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload)
const { error: apiError, response } = await api.POST('/api/users', {
body: {
username: data.get('username'),
initialPassword: data.get('password'),
groupIds: data.getAll('groupIds')
}
});
if (!res.ok) {
const backendError = await parseBackendError(res);
return fail(res.status, { success: false, message: getErrorMessage(backendError?.code) });
if (apiError) {
const code = (apiError as { code?: string })?.code;
return fail(response.status, { success: false, message: getErrorMessage(code) });
}
return { success: true };
},
deleteUser: async ({ request, fetch }) => {
const data = await request.formData();
const id = data.get('id');
const baseUrl = env.API_INTERNAL_URL || 'http://localhost:8080';
const id = data.get('id') as string;
const api = createApiClient(fetch);
const res = await fetch(baseUrl + `/api/users/${id}`, {
method: 'DELETE'
const { error: apiError, response } = await api.DELETE('/api/users/{id}', {
params: { path: { id } }
});
if (!res.ok) {
const backendError = await parseBackendError(res);
return fail(res.status, { success: false, message: getErrorMessage(backendError?.code) });
if (apiError) {
const code = (apiError as { code?: string })?.code;
return fail(response.status, { success: false, message: getErrorMessage(code) });
}
return { success: true };
},
updateTag: async ({ request, fetch }) => {
const data = await request.formData();
const id = data.get('id');
const name = data.get('name');
const baseUrl = env.API_INTERNAL_URL || 'http://localhost:8080';
const id = data.get('id') as string;
const api = createApiClient(fetch);
await fetch(baseUrl + `/api/tags/${id}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name })
const { error: apiError, response } = await api.PUT('/api/tags/{id}', {
params: { path: { id } },
body: { name: data.get('name') }
});
if (apiError) {
const code = (apiError as { code?: string })?.code;
return fail(response.status, { success: false, message: getErrorMessage(code) });
}
return { success: true };
},
deleteTag: async ({ request, fetch }) => {
const data = await request.formData();
const id = data.get('id');
const baseUrl = env.API_INTERNAL_URL || 'http://localhost:8080';
const id = data.get('id') as string;
const api = createApiClient(fetch);
const res = await fetch(baseUrl + `/api/tags/${id}`, { method: 'DELETE' });
if (!res.ok) {
const backendError = await parseBackendError(res);
return fail(res.status, { success: false, message: getErrorMessage(backendError?.code) });
const { error: apiError, response } = await api.DELETE('/api/tags/{id}', {
params: { path: { id } }
});
if (apiError) {
const code = (apiError as { code?: string })?.code;
return fail(response.status, { success: false, message: getErrorMessage(code) });
}
return { success: true };
},
createGroup: async ({ request, fetch }) => {
const baseUrl = env.API_INTERNAL_URL || 'http://localhost:8080';
const data = await request.formData();
const payload = {
name: data.get('name'),
permissions: data.getAll('permissions') // Gets all checked checkboxes
};
const api = createApiClient(fetch);
const res = await fetch(baseUrl + '/api/groups', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload)
const { error: apiError, response } = await api.POST('/api/groups', {
body: {
name: data.get('name'),
permissions: data.getAll('permissions')
}
});
if (!res.ok) {
const backendError = await parseBackendError(res);
return fail(res.status, { success: false, message: getErrorMessage(backendError?.code) });
if (apiError) {
const code = (apiError as { code?: string })?.code;
return fail(response.status, { success: false, message: getErrorMessage(code) });
}
return { success: true };
},
updateGroup: async ({ request, fetch }) => {
const baseUrl = env.API_INTERNAL_URL || 'http://localhost:8080';
const data = await request.formData();
const id = data.get('id');
const payload = {
name: data.get('name'),
permissions: data.getAll('permissions')
};
const id = data.get('id') as string;
const api = createApiClient(fetch);
const res = await fetch(baseUrl + `/api/groups/${id}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload)
const { error: apiError, response } = await api.PATCH('/api/groups/{id}', {
params: { path: { id } },
body: {
name: data.get('name'),
permissions: data.getAll('permissions')
}
});
if (!res.ok) {
const backendError = await parseBackendError(res);
return fail(res.status, { success: false, message: getErrorMessage(backendError?.code) });
if (apiError) {
const code = (apiError as { code?: string })?.code;
return fail(response.status, { success: false, message: getErrorMessage(code) });
}
return { success: true };
},
deleteGroup: async ({ request, fetch }) => {
const baseUrl = env.API_INTERNAL_URL || 'http://localhost:8080';
const data = await request.formData();
const id = data.get('id');
const res = await fetch(baseUrl + `/api/groups/${id}`, { method: 'DELETE' });
const id = data.get('id') as string;
const api = createApiClient(fetch);
if (!res.ok) {
const backendError = await parseBackendError(res);
return fail(res.status, { success: false, message: getErrorMessage(backendError?.code) });
const { error: apiError, response } = await api.DELETE('/api/groups/{id}', {
params: { path: { id } }
});
if (apiError) {
const code = (apiError as { code?: string })?.code;
return fail(response.status, { success: false, message: getErrorMessage(code) });
}
return { success: true };
}

View File

@@ -1,62 +1,61 @@
import { env } from '$env/dynamic/private';
import { createApiClient } from '$lib/api.server';
export async function load({ url, fetch }) {
const baseUrl = env.API_INTERNAL_URL || 'http://localhost:8080';
// 1. Parameter auslesen
const senderId = url.searchParams.get('senderId') || '';
const receiverId = url.searchParams.get('receiverId') || '';
const from = url.searchParams.get('from') || '';
const to = url.searchParams.get('to') || '';
const dir = url.searchParams.get('dir') || 'DESC';
let documents = [];
const api = createApiClient(fetch);
let documents: unknown[] = [];
let senderName = '';
let receiverName = '';
// 2. Fetch-Requests vorbereiten
const requests = [];
const requests: Promise<void>[] = [];
// Dokumente laden (nur wenn beide IDs da sind)
if (senderId && receiverId) {
const query = new URLSearchParams({ senderId, receiverId, dir });
if (from) query.set('from', from);
if (to) query.set('to', to);
requests.push(
fetch(`${baseUrl}/api/documents/conversation?${query}`)
.then(r => r.ok ? r.json() : [])
.then(data => documents = data)
api.GET('/api/documents/conversation', {
params: {
query: {
senderId,
receiverId,
dir,
from: from || undefined,
to: to || undefined
}
}
}).then(({ data }) => { documents = data ?? []; })
);
}
// Namen auflösen für Typeahead Initial Value
if (senderId) {
requests.push(
fetch(`${baseUrl}/api/persons/${senderId}`)
.then(r => r.ok ? r.json() : null)
.then(p => senderName = p ? `${p.firstName} ${p.lastName}` : '')
api.GET('/api/persons/{id}', { params: { path: { id: senderId } } })
.then(({ data }) => {
const p = data as { firstName: string; lastName: string } | undefined;
if (p) senderName = `${p.firstName} ${p.lastName}`;
})
);
}
if (receiverId) {
requests.push(
fetch(`${baseUrl}/api/persons/${receiverId}`)
.then(r => r.ok ? r.json() : null)
.then(p => receiverName = p ? `${p.firstName} ${p.lastName}` : '')
api.GET('/api/persons/{id}', { params: { path: { id: receiverId } } })
.then(({ data }) => {
const p = data as { firstName: string; lastName: string } | undefined;
if (p) receiverName = `${p.firstName} ${p.lastName}`;
})
);
}
// Alles parallel abfeuern
await Promise.all(requests);
return {
documents,
initialValues: {
senderName,
receiverName
},
initialValues: { senderName, receiverName },
filters: { senderId, receiverId, from, to, dir }
};
}

View File

@@ -1,24 +1,21 @@
import { error, redirect } from '@sveltejs/kit';
import { env } from '$env/dynamic/private';
import { parseBackendError, getErrorMessage } from '$lib/errors';
import { createApiClient } from '$lib/api.server';
import { getErrorMessage } from '$lib/errors';
export async function load({ params, fetch }) {
const { id } = params;
const baseUrl = env.API_INTERNAL_URL || 'http://localhost:8080';
const api = createApiClient(fetch);
try {
const res = await fetch(`${baseUrl}/api/documents/${id}`);
const { data, error: apiError, response } = await api.GET('/api/documents/{id}', {
params: { path: { id } }
});
if (res.status === 401) throw redirect(302, '/login');
if (response.status === 401) throw redirect(302, '/login');
if (!res.ok) {
const backendError = await parseBackendError(res);
throw error(res.status, getErrorMessage(backendError?.code));
}
return { document: await res.json() };
} catch (e) {
if (e.status) throw e;
throw error(500, getErrorMessage('INTERNAL_ERROR'));
if (apiError) {
const code = (apiError as { code?: string })?.code;
throw error(response.status, getErrorMessage(code));
}
return { document: data };
}

View File

@@ -1,37 +1,35 @@
import { error, fail, redirect } from '@sveltejs/kit';
import { env } from '$env/dynamic/private';
import { createApiClient } from '$lib/api.server';
import { parseBackendError, getErrorMessage } from '$lib/errors';
export async function load({ params, fetch }) {
const { id } = params;
const baseUrl = env.API_INTERNAL_URL || 'http://localhost:8080';
const api = createApiClient(fetch);
try {
const [docRes, personsRes] = await Promise.all([
fetch(`${baseUrl}/api/documents/${id}`),
fetch(`${baseUrl}/api/persons`)
]);
const [docResult, personsResult] = await Promise.all([
api.GET('/api/documents/{id}', { params: { path: { id } } }),
api.GET('/api/persons')
]);
if (!docRes.ok) {
const backendError = await parseBackendError(docRes);
throw error(docRes.status, getErrorMessage(backendError?.code));
}
if (!personsRes.ok) {
throw error(personsRes.status, getErrorMessage('INTERNAL_ERROR'));
}
return {
document: await docRes.json(),
persons: await personsRes.json()
};
} catch (e) {
if (e.status) throw e;
throw error(500, getErrorMessage('INTERNAL_ERROR'));
if (docResult.error) {
const code = (docResult.error as { code?: string })?.code;
throw error(docResult.response.status, getErrorMessage(code));
}
if (personsResult.error) {
throw error(personsResult.response.status, getErrorMessage('INTERNAL_ERROR'));
}
return {
document: docResult.data,
persons: personsResult.data
};
}
export const actions = {
default: async ({ request, params, fetch }) => {
// Raw fetch is used here because FormData multipart bodies are passed through
// directly from the browser without transformation.
const baseUrl = env.API_INTERNAL_URL || 'http://localhost:8080';
const formData = await request.formData();

View File

@@ -12,19 +12,16 @@ export const actions = {
return fail(400, { error: 'Bitte Benutzername und Passwort eingeben.' });
}
// Wir bauen den Basic Auth Header
const credentials = btoa(`${username}:${password}`);
const authHeader = `Basic ${credentials}`;
// Raw fetch is intentional here: we need to pass an explicit Authorization
// header built from the form data, not the cookie-based auth used elsewhere.
try {
// Test-Request an das Backend (z.B. an den Upload-Endpunkt oder einen speziellen /me Endpunkt)
// Wir nutzen hier http://localhost:8080, da beide Container im selben Netz sind (oder localhost im DevContainer)
const baseUrl = env.API_INTERNAL_URL || 'http://localhost:8080';
const response = await fetch(`${baseUrl}/api/users/me`, {
method: 'GET',
headers: {
'Authorization': authHeader
}
headers: { Authorization: authHeader }
});
if (response.status === 401 || response.status === 403) {
@@ -35,22 +32,18 @@ export const actions = {
return fail(500, { error: getErrorMessage('INTERNAL_ERROR') });
}
// Login erfolgreich! Wir speichern den Header in einem Cookie.
// (In Produktion würde man hier ein Session-Token nutzen, aber für Basic Auth müssen wir es mitschleifen)
cookies.set('auth_token', authHeader, {
path: '/',
httpOnly: true, // JavaScript kann das Cookie nicht lesen (Schutz vor XSS)
httpOnly: true,
sameSite: 'strict',
secure: false, // Auf true setzen, wenn wir HTTPS haben
maxAge: 60 * 60 * 24 // 1 Tag
secure: false, // set to true when HTTPS is available
maxAge: 60 * 60 * 24
});
} catch (e) {
console.error(e);
return fail(500, { error: getErrorMessage('INTERNAL_ERROR') });
}
// Weiterleitung zur Startseite
return redirect(303, '/');
}
} satisfies Actions;

View File

@@ -1,18 +1,12 @@
import { redirect } from '@sveltejs/kit';
import { env } from '$env/dynamic/private';
import { createApiClient } from '$lib/api.server';
export async function load({ url, fetch }) {
const q = url.searchParams.get('q') || '';
const baseUrl = env.API_INTERNAL_URL || 'http://localhost:8080';
const api = createApiClient(fetch);
// Query Parameter an Backend durchreichen
const apiUrl = new URL(`${baseUrl}/api/persons`);
if (q) apiUrl.searchParams.set('q', q);
const { data } = await api.GET('/api/persons', {
params: { query: { q: q || undefined } }
});
const res = await fetch(apiUrl.toString());
if (!res.ok) return { persons: [] };
const persons = await res.json();
return { persons, q };
return { persons: data ?? [], q };
}

View File

@@ -1,27 +1,23 @@
import { error, } from '@sveltejs/kit';
import { env } from '$env/dynamic/private';
import { error } from '@sveltejs/kit';
import { createApiClient } from '$lib/api.server';
import { getErrorMessage } from '$lib/errors';
export async function load({ params, fetch }) {
const { id } = params;
const api = createApiClient(fetch);
const baseUrl = env.API_INTERNAL_URL || 'http://localhost:8080';
const [personResult, docsResult] = await Promise.all([
api.GET('/api/persons/{id}', { params: { path: { id } } }),
api.GET('/api/persons/{id}/documents', { params: { path: { id } } })
]);
try {
// Parallel Fetching: Person Infos + Ihre Dokumente
const [personRes, docsRes] = await Promise.all([
fetch(`${baseUrl}/api/persons/${id}`),
fetch(`${baseUrl}/api/persons/${id}/documents`)
]);
if (personRes.status === 404) throw error(404, 'Person nicht gefunden');
return {
person: await personRes.json(),
documents: await docsRes.json()
};
} catch (e) {
if (e.status) throw e;
throw error(500, 'Ladefehler');
if (personResult.error) {
const code = (personResult.error as { code?: string })?.code;
throw error(personResult.response.status, getErrorMessage(code));
}
return {
person: personResult.data,
documents: docsResult.data ?? []
};
}