Compare commits

..
Author SHA1 Message Date
robin edd33ab712 chore: auto init of database 2026-10-12 16:29:11 +02:00
robin fde1f27745 fix: create song 2026-08-27 17:29:03 +02:00
robin 583ef90a7b fix: POST currentID 2026-08-27 16:26:45 +02:00
robin 2fb484ad26 chore: update .gitignore 2026-08-27 16:16:41 +02:00
24 changed files with 1993 additions and 10744 deletions

No files matched your search

+1
View File
@@ -46,3 +46,4 @@ songs.sqlite
.gitignore
/lib/generated/prisma
pnpm-lock.yaml
+2 -2
View File
@@ -11,13 +11,13 @@ COPY package.json pnpm-lock.yaml* pnpm-workspace.yaml* ./
RUN apk add --no-cache python3 make g++
# Installation mit deiner funktionierenden Workspace-Konfiguration
RUN npm i --frozen-lockfile
RUN pnpm i --frozen-lockfile
FROM base AS builder
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY . .
RUN npm run openapi:generate; npm run build
RUN pnpm run build
FROM base AS runner
WORKDIR /app
+2 -3
View File
@@ -2,7 +2,6 @@
import { error } from "console";
import Papa from "papaparse";
import { addSongToSongbook } from "@/lib/db/managing";
interface CSVRow {
nummer: string;
@@ -31,8 +30,8 @@ export async function uploadCSVAction(formData:FormData) {
console.log("Data:", rows);
rows.forEach(row => {
//console.log(`Nummer: ${row.number}, Titel: ${row.titel}`);
addSongToSongbook(String(row.titel), Number(songbookId), String(row.nummer))
console.log(`Nummer: ${row.nummer}, Titel: ${row.titel}`);
//addSongToSongbook(String(row.titel), Number(songbookId), String(row.nummer))
});
return { success: true, message: `${rows.length} Zeilen erfolgreich importiert.`};
+42 -31
View File
@@ -9,7 +9,7 @@ import { Screens } from "@/components/DatabaseOverview";
interface Songbook {
id: number;
name: string;
title: string;
language: string;
}
@@ -22,7 +22,7 @@ interface Song {
interface SongInfo {
songbook_id: number;
songbook_name: string;
songbook_title: string;
song_number: string;
title: string;
}
@@ -34,7 +34,7 @@ export default function AdminPage() {
const [number, setNumber] = useState("");
const [title, setTitle] = useState("");
const [newBookName, setNewBookName] = useState("");
const [newBookTitle, setNewBookTitle] = useState("");
const [newBookLanguage, setNewBookLanguage] = useState("");
const [uploadStatus, setUploadStatus] = useState<string | null>(null);
@@ -96,21 +96,34 @@ export default function AdminPage() {
}
try {
const res = await fetch("/api/songs", {
// Create song
const res1 = await fetch("/api/songs", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
songbookId: Number(selectedSongbookId),
number: number,
title: title
})
});
if (res.ok) {
alert("Lied erfolgreich hinzugefügt!");
setNumber("");
setTitle("");
})
if (res1.ok) {
console.log("Lied erfolgreich erstellt!");
} else {
alert("Fehler beim Senden.");
console.log("Lied erstellen fehlgeschlagen!");
}
// Attach song to songbook
const data = await res1.json()
const songId = data.song.id;
const res2 = await fetch(`/api/songbooks/${Number(selectedSongbookId)}/songs/${songId}`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
number: number
})
})
if (res2.ok) {
console.log("Lied erfolgreich dem Liederbuch zugewiesen!");
} else {
console.log("Fehler");
}
} catch (error) {
console.error("Failed sending current songID:", error);
@@ -124,19 +137,17 @@ export default function AdminPage() {
}
try {
const res = await fetch("/api/songs/attach", {
const res2 = await fetch(`/api/songbooks/${Number(selectedSongbookId)}/songs/${selectedSong.song_id}`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
songbookId: selectedSongbookId,
songId: selectedSong.song_id,
number: number,
number: number
})
});
if (res.ok) {
alert("Lied erfolgreich zum Liederbuch hinzugefügt!");
})
if (res2.ok) {
console.log("Lied erfolgreich dem Liederbuch zugewiesen!");
} else {
alert("Fehler beim Senden.");
console.log("Fehler");
}
} catch (error) {
console.error("Failed sending current songID:", error);
@@ -169,8 +180,8 @@ export default function AdminPage() {
}
const addSongbook = async () => {
if (!newBookName) {
alert("Der Name des Liederbuches darf nicht leer sein!");
if (!newBookTitle) {
alert("Der Title des Liederbuches darf nicht leer sein!");
return;
}
@@ -178,14 +189,14 @@ export default function AdminPage() {
const res = await fetch("/api/songbooks", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name: newBookName, language: newBookLanguage })
body: JSON.stringify({ title: newBookTitle, language: newBookLanguage })
});
if (res.ok) {
const createdBook = await res.json();
setSongbooks([...songbooks, createdBook]);
alert("Liederbuch erfolgreich erstellt!");
setNewBookName("");
setNewBookTitle("");
setNewBookLanguage("");
} else {
alert("Failed adding songbook!");
@@ -215,8 +226,8 @@ export default function AdminPage() {
<Input.Text
type="text"
placeholder="z.B. Gesangbuch"
value={newBookName}
onChange={(e) => setNewBookName(e.target.value)}
value={newBookTitle}
onChange={(e) => setNewBookTitle(e.target.value)}
/>
</div>
<div>
@@ -248,7 +259,7 @@ export default function AdminPage() {
<option value="">-- Bitte wählen --</option>
{songbooks.map((book) => (
<option key={book.id} value={String(book.id)}>
{book.name}{book.language ? ` (${book.language})` : ""}
{book.title}{book.language ? ` (${book.language})` : ""}
</option>
))}
</Input.Select>
@@ -290,7 +301,7 @@ export default function AdminPage() {
<option value="">-- Bitte wählen --</option>
{songbooks.map((book) => (
<option key={book.id} value={String(book.id)}>
{book.name}{book.language ? ` (${book.language})` : ""}
{book.title}{book.language ? ` (${book.language})` : ""}
</option>
))}
</Input.Select>
@@ -335,7 +346,7 @@ export default function AdminPage() {
<ul className="list-disc list-inside pl-2 text-xs text-neutral-400">
{songInfos.map((info) => (
<li key={info.songbook_id}>
{info.songbook_name} (Nr. {info.song_number})
{info.songbook_title} (Nr. {info.song_number})
</li>
))}
</ul>
@@ -356,7 +367,7 @@ export default function AdminPage() {
<option value="">-- Bitte wählen --</option>
{songbooks.map((book) => (
<option key={book.id} value={String(book.id)}>
{book.name}{book.language ? ` (${book.language})` : ""}
{book.title}{book.language ? ` (${book.language})` : ""}
</option>
))}
</Input.Select>
@@ -390,7 +401,7 @@ export default function AdminPage() {
{songInfos.length > 0 ? (
songInfos.map((info) => (
<option key={info.songbook_id} value={String(info.songbook_id)}>
{info.songbook_name} (Nr. {info.song_number})
{info.songbook_title} (Nr. {info.song_number})
</option>
))
): ""}
-25
View File
@@ -1,25 +0,0 @@
// @/app/api/docs/api/routes.ts
/**
* @openapi
* /api/docs/api:
* get:
* summary: OpenAPI-Spezifikation abrufen
* tags:
* - Docs
* description: Gibt die vollständige OpenAPI-JSON-Spezifikation der API zurück.
* responses:
* 200:
* description: Erfolgreich generierte OpenAPI-Spezifikation.
* content:
* application/json:
* schema:
* type: object
*/
import { NextResponse } from 'next/server';
import spec from '@/src/generated/openapi.json';
export function GET() {
return NextResponse.json(spec);
}
+21 -82
View File
@@ -1,60 +1,40 @@
// @/app/api/songbooks/[songBookId]/route.ts
import { NextResponse } from "next/server";
import { getSongBookById, updateSongBook, deleteSongBook } from "@/lib/db/songbook";
interface RouteParams {
params: Promise<{
songBookId: string;
}>;
};
// import { parseInt } from "@/lib/helper/checkvar";
/**
* @openapi
* /api/songbooks/{songBookId}:
* /api/songbooks/{id}:
* get:
* summary: Einzelnes Songbook abrufen
* summary: Einzelnen Songbook abrufen
* tags:
* - Songbooks
* parameters:
* - in: path
* name: songBookId
* name: id
* required: true
* schema:
* type: integer
* description: Die ID des Songbooks
* example: 1
* responses:
* 200:
* description: Songbook erfolgreich gefunden
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/SongBook'
* 400:
* description: Ungültige Songbook-ID
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
* 404:
* description: Songbook nicht gefunden
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
* 500:
* description: Serverfehler
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
*/
export async function GET(_request: Request, { params }: RouteParams) {
export async function GET(request: Request, { params }) {
try {
const { songBookId } = await params;
const res = await getSongBookById(parseInt(songBookId));
const res = await getSongBookById(songBookId);
if (!res.success) {
return NextResponse.json({ message: res.error }, { status: res.status });
@@ -73,63 +53,39 @@ export async function GET(_request: Request, { params }: RouteParams) {
/**
* @openapi
* /api/songbooks/{songBookId}:
* /api/songbooks/{id}:
* patch:
* summary: Songbook aktualisieren
* tags:
* - Songbooks
* parameters:
* - in: path
* name: songBookId
* name: id
* required: true
* schema:
* type: integer
* description: Die ID des Songbooks
* example: 1
* requestBody:
* required: true
* content:
* application/json:
* schema:
* type: object
* properties:
* title:
* type: string
* example: "Feiert Jesus 1"
* language:
* type: string
* example: "DE"
* responses:
* 200:
* description: Songbook erfolgreich aktualisiert
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/SongBook'
* 400:
* description: Ungültige Parameter oder Daten
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
* 404:
* description: Songbook nicht gefunden
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
* 500:
* description: Serverfehler
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
*/
export async function PATCH(request: Request, { params }: RouteParams) {
export async function PATCH(request: Request, { params }) {
try {
const { songBookId } = await params;
const data = await request.json();
const res = await updateSongBook(parseInt(songBookId), data);
const res = await updateSongBook(songBookId, data);
if (!res.success) {
return NextResponse.json({ message: res.error }, { status: res.status });
@@ -139,7 +95,7 @@ export async function PATCH(request: Request, { params }: RouteParams) {
} catch (error) {
console.error("API Error:", error);
return NextResponse.json(
{ error: "Fehler beim Aktualisieren des Songbooks" },
{ error: "Fehler beim Laden der Songbookinfos" },
{ status: 500 }
);
}
@@ -148,49 +104,32 @@ export async function PATCH(request: Request, { params }: RouteParams) {
/**
* @openapi
* /api/songbooks/{songBookId}:
* /api/songbooks/{id}:
* delete:
* summary: Songbook löschen
* tags:
* - Songbooks
* parameters:
* - in: path
* name: songBookId
* name: id
* required: true
* schema:
* type: integer
* description: Die ID des Songbooks
* example: 1
* responses:
* 200:
* description: Songbook erfolgreich gelöscht (gibt das gelöschte Songbook zurück)
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/SongBook'
* description: Songbook erfolgreich gelöscht
* 400:
* description: Ungültige Songbook-ID
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
* 404:
* description: Songbook nicht gefunden
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
* 500:
* description: Serverfehler
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
*/
export async function DELETE(_request: Request, { params }: RouteParams) {
export async function DELETE(request: Request, { params }) {
try {
const { songBookId } = await params;
const res = await deleteSongBook(parseInt(songBookId));
const res = await deleteSongBook(songBookId);
if (!res.success) {
return NextResponse.json({ message: res.error }, { status: res.status });
@@ -200,7 +139,7 @@ export async function DELETE(_request: Request, { params }: RouteParams) {
} catch (error) {
console.error("API Error:", error);
return NextResponse.json(
{ error: "Fehler beim Löschen des Songbooks" },
{ error: "Fehler beim Laden der Songbookinfos" },
{ status: 500 }
);
}
@@ -1,14 +1,6 @@
// @/app/api/songbooks/[songBookId]/songs/[songId]/route.ts
import { NextResponse } from "next/server";
import { addSongToBook, updateSongInBook, removeSongFromBook } from "@/lib/db/songbooksongs";
interface RouteParams {
params: Promise<{
songBookId: string;
songId: string;
}>;
};
// import { parseInt } from "@/lib/helper/checkvar";
/**
* @openapi
@@ -16,7 +8,7 @@ interface RouteParams {
* post:
* summary: Song zu Liederbuch hinzufügen
* tags:
* - Songbooks
* - Songbook
* parameters:
* - in: path
* name: songBookId
@@ -24,14 +16,12 @@ interface RouteParams {
* schema:
* type: integer
* description: Die ID des Liederbuchs
* example: 1
* - in: path
* name: songId
* required: true
* schema:
* type: integer
* description: Die ID des Songs
* example: 1
* requestBody:
* required: true
* content:
@@ -48,36 +38,20 @@ interface RouteParams {
* responses:
* 200:
* description: Song erfolgreich zugewiesen
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/SongBookEntry'
* 400:
* description: Ungültige Parameter oder fehlende Songnummer
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
* 409:
* description: Songnummer bereits vergeben oder Song existiert bereits im Buch
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
* 500:
* description: Serverfehler
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
*/
export async function POST(request: Request, { params }: RouteParams) {
export async function POST(request: Request, { params }) {
try {
const { songBookId, songId } = await params;
const data = await request.json();
const res = await addSongToBook(parseInt(songId), parseInt(songBookId), String(data.number));
const res = await addSongToBook(songId, songBookId, data.number);
if (!res.success) {
@@ -88,7 +62,7 @@ export async function POST(request: Request, { params }: RouteParams) {
} catch (error) {
console.error("API Error:", error);
return NextResponse.json(
{ error: "Fehler beim Zuweisen des Songs" },
{ error: "Fehler beim Laden der Songbookinfos" },
{ status: 500 }
);
}
@@ -101,7 +75,7 @@ export async function POST(request: Request, { params }: RouteParams) {
* patch:
* summary: Songnummer eines Songs im Liederbuch aktualisieren
* tags:
* - Songbooks
* - Songbook
* parameters:
* - in: path
* name: songBookId
@@ -109,14 +83,12 @@ export async function POST(request: Request, { params }: RouteParams) {
* schema:
* type: integer
* description: Die ID des Liederbuchs
* example: 1
* - in: path
* name: songId
* required: true
* schema:
* type: integer
* description: Die ID des Songs
* example: 1
* requestBody:
* required: true
* content:
@@ -133,40 +105,20 @@ export async function POST(request: Request, { params }: RouteParams) {
* responses:
* 200:
* description: Songnummer erfolgreich aktualisiert
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/SongBookEntry'
* 400:
* description: Ungültige Parameter oder fehlende Daten
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
* 404:
* description: Zuweisung nicht gefunden
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
* 409:
* description: Neue Songnummer bereits vergeben
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
* 500:
* description: Serverfehler
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
*/
export async function PATCH(request: Request, { params }: RouteParams) {
export async function PATCH(request: Request, { params }) {
try {
const { songBookId, songId } = await params;
const data = await request.json();
const res = await updateSongInBook(parseInt(songId), parseInt(songBookId), data);
const res = await updateSongInBook(songId, songBookId, data);
if (!res.success) {
return NextResponse.json({ message: res.error }, { status: res.status });
@@ -176,7 +128,7 @@ export async function PATCH(request: Request, { params }: RouteParams) {
} catch (error) {
console.error("API Error:", error);
return NextResponse.json(
{ error: "Fehler beim Aktualisieren der Songnummer" },
{ error: "Fehler beim Laden der Songbookinfos" },
{ status: 500 }
);
}
@@ -189,7 +141,7 @@ export async function PATCH(request: Request, { params }: RouteParams) {
* delete:
* summary: Song aus Liederbuch entfernen
* tags:
* - Songbooks
* - Songbook
* parameters:
* - in: path
* name: songBookId
@@ -197,45 +149,27 @@ export async function PATCH(request: Request, { params }: RouteParams) {
* schema:
* type: integer
* description: Die ID des Liederbuchs
* example: 1
* - in: path
* name: songId
* required: true
* schema:
* type: integer
* description: Die ID des Songs
* example: 1
* responses:
* 200:
* description: Song erfolgreich aus dem Liederbuch entfernt (gibt die entfernte Zuweisung zurück)
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/SongBookEntry'
* description: Song erfolgreich aus dem Liederbuch entfernt
* 400:
* description: Ungültige Parameter
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
* 404:
* description: Zuweisung nicht gefunden
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
* 500:
* description: Serverfehler
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
*/
export async function DELETE(_request: Request, { params }: RouteParams) {
export async function DELETE(request: Request, { params }) {
try {
const { songBookId, songId } = await params;
const res = await removeSongFromBook(parseInt(songId), parseInt(songBookId));
const res = await removeSongFromBook(songId, songBookId);
if (!res.success) {
return NextResponse.json({ message: res.error }, { status: res.status });
@@ -245,7 +179,7 @@ export async function DELETE(_request: Request, { params }: RouteParams) {
} catch (error) {
console.error("API Error:", error);
return NextResponse.json(
{ error: "Fehler beim Entfernen des Songs" },
{ error: "Fehler beim Laden der Songbookinfos" },
{ status: 500 }
);
}
+8 -46
View File
@@ -1,77 +1,39 @@
// @/app/api/songbooks/[songBookId]/songs/route.ts
import { NextResponse } from "next/server";
import { getSongByNumber } from "@/lib/db/songbooksongs";
interface RouteParams {
params: Promise<{
songBookId: string;
}>;
};
/**
* @openapi
* /api/songbooks/{songBookId}/songs:
* /api/songbooks/{id}/songs:
* get:
* summary: Einen Song nach Nummer in einem Songbook suchen
* tags:
* - Songbooks
* - Songbook
* parameters:
* - in: path
* name: songBookId
* name: id
* required: true
* schema:
* type: integer
* description: Die ID des Songbooks
* example: 1
* - in: query
* name: number
* required: true
* schema:
* type: string
* description: Die Nummer des Songs im Songbook
* example: "123"
* - in: query
* name: n
* required: false
* schema:
* type: string
* description: Alias für `number`
* example: "123"
* responses:
* 200:
* description: Song im Songbook erfolgreich gefunden
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/SongBookEntry'
* description: Songbook erfolgreich gefunden
* 400:
* description: Ungültige Songbook-ID oder fehlender number-Parameter
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
* description: Ungültige Songbook-ID
* 404:
* description: Songbook oder Song nicht gefunden
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
* description: Songbook nicht gefunden
* 500:
* description: Serverfehler
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
*/
export async function GET(request: Request, { params }: RouteParams) {
export async function GET(request: Request, { params }) {
try {
const { songBookId } = await params;
const { searchParams } = new URL(request.url);
const number = searchParams.get("number") || searchParams.get("n");
if(number){
const res = await getSongByNumber(parseInt(songBookId), number);
const res = await getSongByNumber(songBookId, number);
if (!res.success) {
return NextResponse.json({ message: res.error }, { status: res.status });
+21 -47
View File
@@ -1,45 +1,22 @@
// @/app/api/songbooks/route.ts
// @wikiCategory: Liederbücher
import { NextResponse } from "next/server";
import { getSongBooks, searchSongBooksByTitle, createSongBook } from "@/lib/db/songbook";
/**
* @openapi
* /api/songbooks:
* get:
* summary: Get all songbooks or search songbooks by title
* tags:
* - Songbooks
* parameters:
* - in: query
* name: query
* required: false
* schema:
* type: string
* description: Search term for the songbook title
* example: "Feiert Jesus"
* - in: query
* name: q
* required: false
* schema:
* type: string
* description: Alias for `query`
* example: "Feiert Jesus"
* summary: Get all songbooks
* responses:
* 200:
* description: List of songbooks (filtered by title if a query is given)
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: '#/components/schemas/SongBook'
* description: List of songbooks
* 500:
* description: Internal Server Error
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
*
* @wikiDescription: Liste aller Liederbücher abrufen
*/
export async function GET(request: Request) {
try {
@@ -83,8 +60,6 @@ export async function GET(request: Request) {
* /api/songbooks:
* post:
* summary: Creates a new songbook
* tags:
* - Songbooks
* requestBody:
* required: true
* content:
@@ -93,7 +68,6 @@ export async function GET(request: Request) {
* type: object
* required:
* - title
* - language
* properties:
* title:
* type: string
@@ -113,25 +87,25 @@ export async function GET(request: Request) {
* type: boolean
* example: true
* songBook:
* $ref: '#/components/schemas/SongBook'
* type: object
* properties:
* id:
* type: integer
* example: 1
* title:
* type: string
* example: "Feiert Jesus 1"
* language:
* type: string
* example: "DE"
* 400:
* description: Bad Request (missing title or language)
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
* description: Bad Request (missing title)
* 409:
* description: Conflict (title already exists)
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
* 500:
* description: Internal Server Error
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
*
* @wikiDescription: Neues Liederbuch erstellen
*/
export async function POST(request: Request) {
try {
+16 -77
View File
@@ -1,59 +1,36 @@
// @/app/api/songs/[songId]/route.ts
import { NextResponse } from "next/server";
import { getSongById, updateSong, deleteSong } from "@/lib/db/song";
// import { parseInt } from "@/lib/helper/checkvar";
interface RouteParams {
params: Promise<{
songId: string;
}>;
};
/**
* @openapi
* /api/songs/{songId}:
* /api/songs/{id}:
* get:
* summary: Einzelnen Song abrufen
* tags:
* - Songs
* parameters:
* - in: path
* name: songId
* name: id
* required: true
* schema:
* type: integer
* description: Die ID des Songs
* example: 1
* responses:
* 200:
* description: Song erfolgreich gefunden
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Song'
* 400:
* description: Ungültige Song-ID
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
* 404:
* description: Song nicht gefunden
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
* 500:
* description: Serverfehler
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
*/
export async function GET(_request: Request, { params }: RouteParams) {
export async function GET(request: Request, { params }) {
try {
const { songId } = await params;
const res = await getSongById(parseInt(songId));
const res = await getSongById(songId);
if (!res.success) {
return NextResponse.json({ message: res.error }, { status: res.status });
@@ -72,60 +49,39 @@ export async function GET(_request: Request, { params }: RouteParams) {
/**
* @openapi
* /api/songs/{songId}:
* /api/songs/{id}:
* patch:
* summary: Song aktualisieren
* tags:
* - Songs
* parameters:
* - in: path
* name: songId
* name: id
* required: true
* schema:
* type: integer
* description: Die ID des Songs
* example: 1
* requestBody:
* required: true
* content:
* application/json:
* schema:
* type: object
* properties:
* title:
* type: string
* example: "Großer Gott"
* responses:
* 200:
* description: Song erfolgreich aktualisiert
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Song'
* 400:
* description: Ungültige Parameter oder Daten
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
* 404:
* description: Song nicht gefunden
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
* 500:
* description: Serverfehler
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
*/
export async function PATCH(request: Request, { params }: RouteParams) {
export async function PATCH(request: Request, { params }) {
try {
const { songId } = await params;
const data = await request.json();
const res = await updateSong(parseInt(songId), data);
const res = await updateSong(songId, data);
if (!res.success) {
return NextResponse.json({ message: res.error }, { status: res.status });
@@ -135,7 +91,7 @@ export async function PATCH(request: Request, { params }: RouteParams) {
} catch (error) {
console.error("API Error:", error);
return NextResponse.json(
{ error: "Fehler beim Aktualisieren des Songs" },
{ error: "Fehler beim Laden der Songinfos" },
{ status: 500 }
);
}
@@ -144,49 +100,32 @@ export async function PATCH(request: Request, { params }: RouteParams) {
/**
* @openapi
* /api/songs/{songId}:
* /api/songs/{id}:
* delete:
* summary: Song löschen
* tags:
* - Songs
* parameters:
* - in: path
* name: songId
* name: id
* required: true
* schema:
* type: integer
* description: Die ID des Songs
* example: 1
* responses:
* 200:
* description: Song erfolgreich gelöscht (gibt den gelöschten Song zurück)
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Song'
* description: Song erfolgreich gelöscht
* 400:
* description: Ungültige Song-ID
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
* 404:
* description: Song nicht gefunden
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
* 500:
* description: Serverfehler
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
*/
export async function DELETE(_request: Request, { params }: RouteParams) {
export async function DELETE(request: Request, { params }) {
try {
const { songId } = await params;
const res = await deleteSong(parseInt(songId));
const res = await deleteSong(songId);
if (!res.success) {
return NextResponse.json({ message: res.error }, { status: res.status });
@@ -196,7 +135,7 @@ export async function DELETE(_request: Request, { params }: RouteParams) {
} catch (error) {
console.error("API Error:", error);
return NextResponse.json(
{ error: "Fehler beim Löschen des Songs" },
{ error: "Fehler beim Laden der Songinfos" },
{ status: 500 }
);
}
+27 -54
View File
@@ -1,51 +1,27 @@
// @/app/api/songs/route.ts
// @wikiCategory: Lieder
import { NextResponse } from "next/server";
import { getSongs, searchSongsByTitle, createSong } from "@/lib/db/song";
import { getSongs, searchSongsByTitle, createSong, } from "@/lib/db/song";
/**
* @openapi
* /api/songs:
* get:
* summary: Get all songs or search songs by title
* tags:
* - Songs
* parameters:
* - in: query
* name: query
* required: false
* schema:
* type: string
* description: Search term for the song title
* example: "Großer Gott"
* - in: query
* name: q
* required: false
* schema:
* type: string
* description: Alias for `query`
* example: "Großer Gott"
* summary: Get all songs
* responses:
* 200:
* description: List of songs (filtered by title if a query is given)
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: '#/components/schemas/Song'
* description: List of songs
* 500:
* description: Internal Server Error
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
*/
export async function GET(request: Request) {
try {
const { searchParams } = new URL(request.url);
const query = searchParams.get("query") || searchParams.get("q");
if (query) {
const res = await searchSongsByTitle(query/*, 20*/); // You can enter a limit (default: 20)
@@ -66,7 +42,7 @@ export async function GET(request: Request) {
return NextResponse.json(res.songs, { status: res.status });
} catch (error) {
console.error("GET /api/songs error:", error);
console.error("POST /api/songs error:", error);
return NextResponse.json(
{ message: "Internal Server Error" },
{ status: 500 }
@@ -74,13 +50,12 @@ export async function GET(request: Request) {
}
}
/**
* @openapi
* /api/songs:
* post:
* summary: Creates a new song
* tags:
* - Songs
* requestBody:
* required: true
* content:
@@ -88,14 +63,14 @@ export async function GET(request: Request) {
* schema:
* type: object
* required:
* - title
* - name
* properties:
* title:
* name:
* type: string
* example: "Großer Gott"
* responses:
* 201:
* description: Song successfully created
* description: Songbook successfully created
* content:
* application/json:
* schema:
@@ -104,26 +79,21 @@ export async function GET(request: Request) {
* success:
* type: boolean
* example: true
* song:
* $ref: '#/components/schemas/Song'
* songBook:
* type: object
* properties:
* id:
* type: integer
* example: 1
* title:
* type: string
* example: "Großer Gott"
* 400:
* description: Bad Request (missing title)
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
* description: Bad Request (missing name)
* 409:
* description: Conflict (title already exists)
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
* 500:
* description: Internal Server Error
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
*/
export async function POST(request: Request) {
try {
@@ -131,7 +101,7 @@ export async function POST(request: Request) {
if (!data.title) {
return NextResponse.json(
{ message: "Field 'title' is required" },
{ message: "Field 'title' is required"},
{ status: 400 }
);
}
@@ -140,7 +110,10 @@ export async function POST(request: Request) {
if (!res.success) {
return NextResponse.json(
{ message: res.error },
{
message: res.error,
song: res.song
},
{ status: res.status }
);
}
+77
View File
@@ -0,0 +1,77 @@
// @wikiCategory: Stream
import { NextResponse } from "next/server";
import { getSongById } from "@/lib/db/song";
let currentSong = {
songID: "",
songbook: "",
number: "",
title: ""
};
// @wikiDescription: Akutell gestreamtes Lied abrufen
export async function GET() {
return NextResponse.json(currentSong)
}
// @wikiDescription: Lied zum Streamen festlegen
export async function POST(request: Request) {
try {
const data = await request.json();
const { songID, songbookID } = data;
if (!songID || !songbookID) {
return NextResponse.json(
{ success: false, error: "Fields incomplete!" },
{ status: 400 }
);
}
const result = await getSongById(songID);
if (result.success && result.song) {
const song = result.song;
// looking for the songbook with matching ID
const matchedBook = song.songBooks.find(
(entry) => String(entry.book.id) === String(songbookID)
);
if (matchedBook) {
currentSong = {
songID: String(song.id),
songbook: matchedBook.book.title,
number: String(matchedBook.songNumber),
title: song.title,
};
} else {
// song does exist but not in the given songbook
currentSong = {
songID: "",
songbook: "",
number: "",
title: "",
};
}
} else {
// song does not exist
currentSong = {
songID: "",
songbook: "",
number: "",
title: "",
};
}
console.log("Aktualisierter currentSong:", currentSong);
return NextResponse.json({ success: true, currentSong });
} catch (error) {
console.error("API POST Error:", error);
return NextResponse.json(
{ success: false, error: "Server-Fehler" },
{ status: 500 }
);
}
}
-161
View File
@@ -1,161 +0,0 @@
// @/app/api/stream/route.ts
import { NextResponse } from "next/server";
/**
* @openapi
* components:
* schemas:
* StreamError:
* type: object
* properties:
* success:
* type: boolean
* example: false
* error:
* type: string
* example: "Fields incomplete!"
*/
let currentSong = {
number: "",
song: "",
songbook: "",
};
const clients = new Set<ReadableStreamDefaultController>();
/**
* @openapi
* /api/stream:
* get:
* summary: Aktuell gestreamtes Lied abrufen (Server-Sent Events)
* description: Öffnet einen SSE-Stream. Beim Verbinden wird das aktuelle Lied gesendet (falls gesetzt), danach bei jeder Änderung ein neues Event.
* tags:
* - Stream
* responses:
* 200:
* description: Event-Stream mit dem aktuellen Lied
* content:
* text/event-stream:
* schema:
* type: string
* example: 'data: {"number":"104a","song":"Großer Gott","songbook":"Feiert Jesus 1"}'
*/
export async function GET() {
let controllerRef: ReadableStreamDefaultController;
const stream = new ReadableStream({
start(controller) {
controllerRef = controller;
clients.add(controller);
if (currentSong.song) {
controller.enqueue(`data: ${JSON.stringify(currentSong)}\n\n`);
}
},
cancel() {
clients.delete(controllerRef);
},
});
return new NextResponse(stream, {
headers: {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive',
},
});
}
/**
* @openapi
* /api/stream:
* post:
* summary: Lied zum Streamen festlegen
* description: Setzt das aktuelle Lied und sendet es an alle verbundenen Stream-Clients.
* tags:
* - Stream
* requestBody:
* required: true
* content:
* application/json:
* schema:
* type: object
* required:
* - song
* - songBook
* - number
* properties:
* song:
* type: string
* example: "Großer Gott"
* songBook:
* type: string
* example: "Feiert Jesus 1"
* number:
* type: string
* example: "104a"
* responses:
* 200:
* description: Lied gesetzt und an alle Clients gesendet
* content:
* application/json:
* schema:
* type: object
* properties:
* success:
* type: boolean
* example: true
* currentSong:
* type: object
* properties:
* number:
* type: string
* example: "104a"
* song:
* type: string
* example: "Großer Gott"
* songbook:
* type: string
* example: "Feiert Jesus 1"
* 400:
* description: Felder unvollständig
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/StreamError'
* 500:
* description: Serverfehler
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/StreamError'
*/
export async function POST(request: Request) {
try {
const data = await request.json();
const song = data.song?.trim() ?? null;
const songbook = data.songBook?.trim() ?? null;
const number = data.number?.trim() ?? null;
if (song == null || songbook == null || number == null) {
return NextResponse.json({ success: false, error: "Fields incomplete!" }, { status: 400 });
}
currentSong = {
song,
songbook,
number
};
clients.forEach((controller) => {
controller.enqueue(`data: ${JSON.stringify(currentSong)}\n\n`);
});
return NextResponse.json({ success: true , currentSong }, { status: 200 });
} catch (error) {
return NextResponse.json({ success: false, error: "Server-Fehler" }, { status: 500 });
}
}
-8
View File
@@ -1,8 +0,0 @@
'use client';
import SwaggerUI from 'swagger-ui-react';
import 'swagger-ui-react/swagger-ui.css';
export default function DocsPage() {
return <SwaggerUI url="/api/docs/api" />;
}
+34
View File
@@ -0,0 +1,34 @@
import { getAllApis } from "@/lib/wiki";
import Article from '@/components/wiki/Article';
import { API } from '@/components/mdx-components';
export default async function Page() {
const allApis = await getAllApis();
// Gruppiert die APIs nach ihrer Kategorie
const groupedApis = Object.groupBy(allApis, (api) => api.category);
return (
<Article title="API-Endpunkte">
{Object.entries(groupedApis).map(([category, apis]) => (
<div key={category} className="mb-10">
{/* Kategorie-Überschrift wird nur EINMAL pro Kategorie gerendert */}
<h2 className="text-2xl font-bold text-white mt-10 mb-4 border-b border-zinc-800 pb-2">
{category}
</h2>
{/* Routen innerhalb dieser Kategorie durchgehen */}
{apis?.map((api, index) => (
<div key={index} className="my-4">
{api.methods.map((method, mIndex) => (
<API route={api.route} method={method.method} key={mIndex}>
{method.description}
</API>
))}
</div>
))}
</div>
))}
</Article>
);
}
+14 -12
View File
@@ -1,7 +1,7 @@
import { useState, useEffect, ComponentPropsWithoutRef } from "react";
import Card from "./Card"
import { Input } from "./FormElements"
import Card from "./Card";
import { Input } from "./FormElements";
interface SongsProps extends Omit<ComponentPropsWithoutRef<typeof Card>, "title" | "children"> {
onSelectSong?: (song: Song) => void;
@@ -9,7 +9,7 @@ interface SongsProps extends Omit<ComponentPropsWithoutRef<typeof Card>, "title"
}
interface Song {
song_id: number;
id: number;
songbook_id: number;
song_number: string;
title: string;
@@ -17,17 +17,16 @@ interface Song {
interface Songbook {
id: number;
name: string;
title: string;
language: string;
}
function Songs({ actionName, onSelectSong, className = "", ...props }: SongsProps) {
function Songs({ actionName = "Auswählen", onSelectSong, className = "", ...props }: SongsProps) {
const [song_search_name, setSongSearchName] = useState("");
const [searchResults, setSearchResults] = useState<Song[]>([]);
const [allSongs, setAllSongs] = useState<Song[]>([]);
const [songbooks, setSongbooks] = useState<Songbook[]>([]);
const search = (query: string) => {
setSongSearchName(query);
if (query.trim() !== "") {
@@ -53,7 +52,7 @@ function Songs({ actionName, onSelectSong, className = "", ...props }: SongsProp
}
} catch (error) {
setAllSongs([]);
console.error("Failed fetching songslist!");
console.error("Failed fetching songslist!", error);
}
};
@@ -68,6 +67,7 @@ function Songs({ actionName, onSelectSong, className = "", ...props }: SongsProp
console.error("Loading songbooks failed: ", error);
}
}
loadSongbooks();
getSongslist();
}, []);
@@ -86,6 +86,7 @@ function Songs({ actionName, onSelectSong, className = "", ...props }: SongsProp
onChange={(e) => search(e.target.value)}
/>
</div>
{/* TABELLE */}
<div className="flex-1 min-h-0 overflow-auto border border-neutral-200 dark:border-neutral-800 rounded-lg bg-white dark:bg-black">
<table className="w-full text-left border-collapse text-sm">
@@ -105,16 +106,17 @@ function Songs({ actionName, onSelectSong, className = "", ...props }: SongsProp
) : (
searchResults.map((song) => {
const songBook = songbooks.find((book) => book.id === song.songbook_id);
return (
<tr key={`${song.songbook_id}-${song.song_id}`} className="hover:bg-neutral-100/60 dark:hover:bg-neutral-900/40 transition">
<tr key={`${song.songbook_id}-${song.id}`} className="hover:bg-neutral-100/60 dark:hover:bg-neutral-900/40 transition">
<td className="p-3 font-medium text-neutral-900 dark:text-white max-w-[180px] sm:max-w-none truncate">
{song.title}
<span className="block text-xs text-neutral-500 dark:text-neutral-400 sm:hidden mt-0.5">
{songBook ? songBook.name : "Unbekannt"}
{songBook ? songBook.title : "Unbekannt"}
</span>
</td>
<td className="p-3 text-neutral-700 dark:text-neutral-300 hidden sm:table-cell">
{songBook ? songBook.name : "Unbekannt"}
{songBook ? songBook.title : "Unbekannt"}
</td>
<td className="p-3 text-center font-mono text-blue-600 dark:text-blue-400 font-bold">
{song.song_number}
@@ -135,9 +137,9 @@ function Songs({ actionName, onSelectSong, className = "", ...props }: SongsProp
</table>
</div>
</Card>
)
);
}
export const Screens = {
Songs: Songs,
}
};
-42
View File
@@ -1,42 +0,0 @@
export interface Song {
id: number;
title: string;
}
export interface SongBook {
id: number;
title: string;
language?: string;
}
export interface SongDetailed {
song: {
id: number;
title: string;
songBooks?:{songNumber: number; book:SongBook}[]
};
}
export type APIResponse<T> =
| { success: true; status: number; data: T }
| { success: false; status: number; error: string };
export type GetSongsResponse = APIResponse<Song[]>;
export type GetSongDetailedResponse =
| {
success: true;
status: number;
song: SongDetailed
}
| { success: false; status: number; error: string };
export type GetSongsDelailedResponse =
| {
success: true;
status: number;
songs: SongDetailed[]
}
| { success: false; status: number; error: string };
export type CreateSongsResponse = APIResponse<Song>;
+8 -15
View File
@@ -1,14 +1,7 @@
import { prisma } from "@/lib/db/prisma";
import { parseInt } from "@/lib/helper/checkvar";
import type * as API from "./response";
// For Error checking use this import: import { Prisma } from "@prisma/client";
interface Response {
success: boolean;
status: number;
songs?: [];
error?: string;
}
/**
* GetSongs
@@ -16,7 +9,7 @@ interface Response {
*
* @returns {"success": boolean, "status": number, "songs": [{"id":number, "title": string},...]}
*/
export async function getSongs(): Promise<API.GetSongsResponse> {
export async function getSongs() {
try{
const songs = await prisma.song.findMany({
select: {
@@ -42,7 +35,7 @@ export async function getSongs(): Promise<API.GetSongsResponse> {
* @param id - ID indicatin the song
* @returns {"success": boolean, "status": number, "song": {"id":number, "title": string, "songBooks": [{"songNumber": number, "book": {"title": string, "language": string}},...]}}
*/
export async function getSongById(rawId: number): Promise<API.GetSongDetailedResponse> {
export async function getSongById(rawId: number) {
try{
const id = parseInt(rawId);
if (!id) {
@@ -85,13 +78,13 @@ export async function getSongById(rawId: number): Promise<API.GetSongDetailedRes
*
* @param query - The search term for the song title.
* @param limit - Max number of songs returned for performance (default: 20).
* @returns {"success": boolean, "status": number, "song": {"id":number, "title": string, "songBooks": [{"songNumber": number, "book": {"title": string, "language": string}},...]}}
* @returns @returns {"success": boolean, "status": number, "song": {"id":number, "title": string, "songBooks": [{"songNumber": number, "book": {"title": string, "language": string}},...]}}
*/
export async function searchSongsByTitle(query: string, limit: number = 20): Promise<API.GetSongsDelailedResponse> {
export async function searchSongsByTitle(query: string, limit: number = 20) {
try {
const cleanQuery = query.trim();
if (!cleanQuery) {
return { success: true, status: 200, songs: [] };
return { success: true, songBooks: [] };
}
const songs = await prisma.song.findMany({
@@ -131,7 +124,7 @@ export async function searchSongsByTitle(query: string, limit: number = 20): Pro
* @param data - object with title
* @returns {"success": boolean, "status": number, "song": {"id":number, "title": string}}
*/
export async function createSong(data: { title: string }): Promise<API.CreateSongsResponse> {
export async function createSong(data: { title: string }) {
try{
if(!data.title){
return { success: false, status: 400, error: "Field 'title' is required" };
@@ -171,7 +164,7 @@ export async function createSong(data: { title: string }): Promise<API.CreateSon
export async function updateSong(
rawId: number,
data: { title?: string }
): Promise<API.CreateSongsResponse> {
) {
try {
const id = parseInt(rawId);
if (!id) {
@@ -220,7 +213,7 @@ export async function updateSong(
* @param id - ID indicatin the song
* @returns {"success": boolean, "status": number, "song": {"id": number, "title": string}}
*/
export async function deleteSong(rawId: number): Promise<API.CreateSongsResponse> {
export async function deleteSong(rawId: number) {
try {
const id = parseInt(rawId);
if (!id) {
+1 -1
View File
@@ -1,6 +1,6 @@
export function parseInt(rawInteger: number){
export function parseInt(rawInteger){
const integer = Number.parseInt(rawInteger);
if (Number.isNaN(integer) || !Number.isInteger(integer)) {
+228
View File
@@ -0,0 +1,228 @@
import fs from 'fs';
import path from 'path';
import matter from 'gray-matter';
import ts from 'typescript';
import { ApiRoute, ApiMethod } from '@/types/api';
export type WikiArticle = {
slug: string;
title: string;
rawContent: string;
updatedAt?: string;
};
export type WikiPage = {
title: string;
path: string;
}
const wikiDirectory = path.join(process.cwd(), "data/wiki/pages");
export async function getWikiPageBySlug(slug: string): Promise<WikiArticle | null> {
try {
const fullPath = path.join(wikiDirectory, `${slug}.mdx`);
const fileContents = fs.readFileSync(fullPath, "utf-8");
const { data, content } = matter(fileContents);
return {
slug,
rawContent: content,
title: data.title || 'Unbenannt',
updatedAt: data.updatedAt || null,
...data,
} as WikiArticle;
} catch (error) {
return null;
}
}
/**
* Liest rekursiv alle Dateien aus einem Verzeichnis aus.
* @param dirPath - Der Startordner
* @param extension - Optionale Dateiendung zur Filterung (z. B. ".ts" oder "ts")
* @returns Array mit den Dateipfaden
*/
export function getAllFiles(dirPath: string, extension?: string): string[] {
if (!fs.existsSync(dirPath)) return [];
let results: string[] = [];
// optionales führendes Dot sicherstellen (z. B. aus "ts" wird ".ts")
const targetExt = extension && !extension.startsWith('.')
? `.${extension}`
: extension;
// withFileTypes: true spart zusätzliche fs.statSync Aufrufe
const entries = fs.readdirSync(dirPath, { withFileTypes: true });
for (const entry of entries) {
const fullPath = path.join(dirPath, entry.name);
if (entry.isDirectory()) {
results = results.concat(getAllFiles(fullPath, targetExt));
} else if (!targetExt || entry.name.endsWith(targetExt)) {
results.push(fullPath);
}
}
return results;
}
/**
* Liest die Kategorie aus der Datei aus (@wikiCategory) oder ermittelt sie aus dem Ordnernamen.
*/
export function filterCategory(
content: string,
filePath: string,
prefix: string = '@wikiCategory'
): string {
// 1. In Kommentaren nach @wikiCategory suchen
const lines = content.split('\n');
for (const line of lines) {
const cleaned = line.replace(/^\/\/\s*/, '').replace(/^\/\*\*?\s*/, '').replace(/\*\/$/, '').trim();
if (cleaned.startsWith(prefix)) {
let category = cleaned.slice(prefix.length).trim().replace(/^:\s*/, '');
if (category) return category;
}
}
// 2. Fallback: Ersten Ordnernamen unter app/api/ als Kategorie nutzen
const normalizedPath = filePath.replace(/\\/g, '/');
const apiMatch = normalizedPath.match(/app\/api\/([^/]+)/);
if (apiMatch && apiMatch[1]) {
const folderName = apiMatch[1];
// Ersten Buchstaben großschreiben (z. B. "stream" -> "Stream")
return folderName.charAt(0).toUpperCase() + folderName.slice(1);
}
return 'Allgemein';
}
/**
* Parst TypeScript-Code via AST und extrahiert HTTP-Methoden sowie deren Kommentare.
*/
export function filterMethods(
content: string,
prefix: string = '@wikiDescription'
): ApiMethod[] {
const sourceFile = ts.createSourceFile(
'temp.ts',
content,
ts.ScriptTarget.Latest,
/* setParentNodes */ true
);
const methods: ApiMethod[] = [];
const validMethods = new Set(['GET', 'POST', 'PUT', 'PATCH', 'DELETE']);
ts.forEachChild(sourceFile, (node) => {
if (ts.isFunctionDeclaration(node) && node.name) {
const functionName = node.name.text;
if (validMethods.has(functionName)) {
let description = '';
const commentRanges = ts.getLeadingCommentRanges(content, node.pos);
if (commentRanges && commentRanges.length > 0) {
const lastCommentRange = commentRanges[commentRanges.length - 1];
const rawComment = content.substring(
lastCommentRange.pos,
lastCommentRange.end
);
const cleanedComment = rawComment
.replace(/^\/\/\s*/, '')
.replace(/^\/\*\*?\s*/, '')
.replace(/\*\/$/, '')
.split('\n')
.map((line) => line.replace(/^\s*\*\s?/, '').trim())
.join(' ')
.trim();
if (cleanedComment.startsWith(prefix)) {
let textAfterPrefix = cleanedComment.slice(prefix.length).trim();
textAfterPrefix = textAfterPrefix.replace(/^:\s*/, '');
description = textAfterPrefix;
}
}
methods.push({
method: functionName,
description: description || 'Keine Beschreibung vorhanden.',
});
}
}
});
return methods;
}
/**
* Liest alle API-Dateien dynamisch aus und wandelt sie in ApiRoute-Objekte um.
*/
export async function getAllApis(): Promise<ApiRoute[]> {
try {
const apiBasePath = path.join(process.cwd(), "app/api");
const allTsFiles = getAllFiles(apiBasePath, ".ts");
const routes: ApiRoute[] = [];
allTsFiles.forEach((filePath) => {
const fileContents = fs.readFileSync(filePath, "utf-8");
// 1. Methoden extrahieren
const methods = filterMethods(fileContents, "@wikiDescription");
// Nur Routen hinzufügen, die auch API-Methoden exportieren
if (methods.length > 0) {
// 2. Kategorie ermitteln
const category = filterCategory(fileContents, filePath, "@wikiCategory");
// 3. Route-Pfad automatisch aus dem Dateipfad generieren (app/api/stream/currentID/route.ts -> stream/currentID)
const relativePath = path.relative(apiBasePath, filePath).replace(/\\/g, '/');
const routePath = relativePath
.replace(/\/route\.ts$/, '')
.replace(/\.ts$/, '');
routes.push({
route: routePath,
category,
methods,
});
}
});
return routes;
} catch (error) {
console.error("Fehler beim Auslesen der API-Dateien:", error);
return [];
}
}
export async function getAllWikiPages(): Promise<WikiPage[]> {
try {
const pagesBasePath = path.join(process.cwd(), "data/wiki/pages");
const allPaths = getAllFiles(pagesBasePath, ".mdx");
const allPages: WikiPage[] = [];
for (const filePath of allPaths) {
// extract filename of the path (e. g. "test" at "data/wiki/pages/test.mdx")
const slug = path.parse(filePath).name;
const wikiPage = await getWikiPageBySlug(slug);
if (wikiPage) {
allPages.push({
path: slug,
title: wikiPage.title,
});
}
}
console.log(allPages);
return allPages;
} catch (error) {
console.error("Fehler beim Auslesen der Wiki-Seiten:", error);
return [];
}
}
+1469 -8859
View File
File diff suppressed because it is too large. Load diff
+8 -9
View File
@@ -7,19 +7,23 @@
"build": "next build",
"start": "next start",
"lint": "eslint",
"openapi:generate": "node scripts/generate-openapi.mjs"
"postinstall": "prisma generate",
"predev": "prisma migrate deploy",
"prestart": "prisma migrate deploy",
"db:setup": "node -e \"require('fs').existsSync('.env')||require('fs').copyFileSync('example.env','.env')\" && prisma migrate deploy && prisma generate"
},
"dependencies": {
"@prisma/adapter-better-sqlite3": "^7.9.1",
"@prisma/client": "^7.10.0",
"@prisma/client": "^7.9.1",
"@types/papaparse": "^5.5.2",
"argon2": "^0.45.1",
"better-sqlite3": "^13.0.2",
"dotenv": "^17.4.2",
"gray-matter": "^4.0.3",
"next": "^16.4.0",
"next": "16.2.9",
"next-mdx-remote": "^6.0.0",
"papaparse": "^5.5.4",
"prisma": "^7.9.1",
"react": "19.2.4",
"react-dom": "19.2.4",
"rehype-autolink-headings": "^7.1.0",
@@ -31,8 +35,7 @@
"remark-html": "^16.0.1",
"remark-parse": "^11.0.0",
"remark-rehype": "^11.1.2",
"shiki": "^4.4.1",
"swagger-ui-react": "^5.33.2"
"shiki": "^4.4.1"
},
"devDependencies": {
"@tailwindcss/postcss": "^4",
@@ -41,12 +44,8 @@
"@types/node": "^20",
"@types/react": "^19",
"@types/react-dom": "^19",
"@types/swagger-jsdoc": "^6.0.4",
"@types/swagger-ui-react": "^5.18.0",
"eslint": "^9",
"eslint-config-next": "16.2.9",
"prisma": "^8.0.0-rc.22",
"swagger-jsdoc": "^6.3.0",
"tailwindcss": "^4",
"typescript": "^5.9.3"
},
-18
View File
@@ -1,18 +0,0 @@
import swaggerJsdoc from 'swagger-jsdoc';
import { mkdirSync, writeFileSync } from 'node:fs';
import { dirname } from 'node:path';
const spec = swaggerJsdoc({
definition: {
openapi: '3.0.0',
info: { title: 'PsalmTafel API', version: '1.0.0' },
},
apis: ['./app/api/**/*.ts'],
failOnErrors: true,
});
const out = 'src/generated/openapi.json';
mkdirSync(dirname(out), { recursive: true });
writeFileSync(out, JSON.stringify(spec, null, 2));
console.log(`OpenAPI: ${Object.keys(spec.paths ?? {}).length} Pfade -> ${out}`);
File diff suppressed because it is too large. Load diff