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
Rudi 5c9a96357b get song id now returns bookId too 2026-08-27 15:49:45 +02:00
Rudi 7cbbd5466f Bruno file added (API) 2026-08-27 15:49:23 +02:00
Rudi f026db0b68 Merge Konflict
Ist jetzt auf stand von main
2026-08-27 15:18:38 +02:00
Rudi 496a70ffed Update on Songbooksongs number
Number of Song in a Songbook is not number anymore but string
so "3a" would work.
2026-08-27 15:00:04 +02:00
Rudi b060ab29cf API work on SongbookSongs 2026-08-27 14:59:19 +02:00
Rudi 4bdf03426c Work in Songs and Songbooks API 2026-08-27 13:26:50 +02:00
Rudi e1eaea0f17 Added helper file 'checkvars'
In this file comes the code to check the input from the User
e.g. is `id` an integer
2026-08-27 13:26:20 +02:00
robin 941f7aa729 Merge pull request 'Style/adjust receiver page' (#42) from style/adjust-receiver-page into main
Deploy Next.js via Docker / deploy (push) Successful in 1m11s
Reviewed-on: Schanbro/PsalmTafel#42
2026-08-27 09:45:29 +00:00
robin 1088cfd5fd fix: merged conflicts 2026-08-27 11:44:23 +02:00
robin b3870265f6 Merge remote-tracking branch 'Gitea/main' into style/adjust-receiver-page 2026-08-27 11:44:18 +02:00
robin 9c7029bad5 style: adjust receiver page 2026-08-26 15:28:41 +02:00
robin 5afdae2b20 Merge pull request 'Feat/wiki' (#40) from feat/wiki into main
Deploy Next.js via Docker / deploy (push) Successful in 1m2s
Reviewed-on: Schanbro/PsalmTafel#40
2026-08-26 12:47:35 +00:00
robin 59e65e257e Merge branch 'main' into feat/wiki 2026-08-26 12:47:26 +00:00
robin ee6169d948 fix: small issue 2026-08-26 14:46:22 +02:00
robin 9610884703 previous 2026-08-25 12:35:28 +02:00
robin 675c046029 feat: list all wikiPages on the index page 2026-08-25 12:34:47 +02:00
robin 1d34622b39 feat: create wikiIndexPage 2026-08-25 11:54:10 +02:00
robin 9dbbd56664 Merge pull request 'style: adjust Callout style' (#39) from feat/wiki into main
Deploy Next.js via Docker / deploy (push) Successful in 1m14s
Reviewed-on: Schanbro/PsalmTafel#39
2026-08-25 09:49:13 +00:00
robin dba41634ae Merge branch 'main' into feat/wiki 2026-08-25 09:49:08 +00:00
robin 4ebe47e7fa style: adjust Callout style 2026-08-25 11:47:06 +02:00
robin e08ef095e0 Merge pull request 'Feat/wiki' (#38) from feat/wiki into main
Deploy Next.js via Docker / deploy (push) Successful in 5m26s
Reviewed-on: Schanbro/PsalmTafel#38
2026-08-06 15:42:35 +00:00
robin a414f80d0d Merge branch 'main' into feat/wiki 2026-08-06 15:42:26 +00:00
robin 11ebeafdcd chore: wiki: automatic categories 2026-08-06 17:41:37 +02:00
robin 3fc0697db8 chore: wiki: automatic list of all api endpoints 2026-08-06 17:39:51 +02:00
robin 7664d058df chore: wiki: add callout to api wiki page 2026-08-06 16:35:16 +02:00
robin 324e5fca9b chore: wiki: move api wiki to own page 2026-08-06 16:32:43 +02:00
robin 28dc1ce6b1 chore: wiki: add component Article 2026-08-06 16:29:39 +02:00
robin 3c3a4e309a chore: wiki: add API component and add test 2026-08-06 15:02:10 +02:00
robin 91dafe6a06 chore: readme: update installtion wiki link 2026-08-06 14:42:07 +02:00
robin c4f29ef78b Merge pull request 'Feat/wiki' (#37) from feat/wiki into main
Deploy Next.js via Docker / deploy (push) Successful in 3m57s
Reviewed-on: Schanbro/PsalmTafel#37
2026-08-05 10:58:32 +00:00
robin 025ac63275 Merge branch 'main' into feat/wiki 2026-08-05 10:58:15 +00:00
robin e600ba302d feat: wiki: create api page 2026-08-05 12:55:26 +02:00
robin bf8e78d0ba feat: add heading anchor links 2026-08-05 12:52:20 +02:00
robin e403677a71 chore: wiki: add createSongbook 2026-08-05 12:42:27 +02:00
robin 71df1a8384 chore: wiki: add createSong 2026-08-05 12:38:17 +02:00
robin ed2c47aab2 feat: copy button 2026-08-05 12:21:40 +02:00
robin da99471ca5 chore: update wiki 2026-08-05 12:11:52 +02:00
robin 975aba1020 feat: show language on code blocks 2026-08-04 16:12:14 +02:00
robin aee4b8c567 style: adjust style 2026-08-04 16:02:02 +02:00
robin 592b1a158a style: add automatic colors to code 2026-08-04 15:53:13 +02:00
robin 14be41befd fix: fixed html nest issue 2026-08-04 15:40:25 +02:00
robin 3d82ef9671 style: add more components and add test wiki page 2026-08-04 15:37:30 +02:00
robin fd4da2a43f fix: "'article' is possibly 'null'." 2026-08-04 15:32:45 +02:00
robin 18f8496af9 refactor: switched to mdx for better styling 2026-08-04 15:32:04 +02:00
robin 5e78869cbf chore: insert installation and setup wiki 2026-08-04 15:21:48 +02:00
robin 49ed2577ac feat: add own wiki 2026-08-04 15:20:31 +02:00
robin 5f41e47958 chore: install packages for markdown support 2026-08-04 15:06:10 +02:00
robin 9d1fe7e1fc feat: add index page for wiki 2026-08-04 14:56:50 +02:00
robin e3bcb96c4f style: set h1 font-size to 2rem 2026-08-04 14:56:19 +02:00
rudi 66c9dc28fc Some API changes in Song. Added '.trim()' for better string processing 2026-08-03 08:16:55 +02:00
rudi 61f1eb5a2c Fix: Typo
Fehlende klammer
2026-07-31 16:57:18 +02:00
rudi e81e6b5743 Added Status takes from helpermethods
Die Helfermethoden (/lib/db/*) bieten Statuscodes, welche hier übernommen wurden.
2026-07-31 16:00:40 +02:00
rudi 25a253116c Merge remote-tracking branch 'origin/refactor/migration-to-prisma' into refactor/songbook-api-integration 2026-07-31 15:56:46 +02:00
rudi 5ca801e9b4 Added status Codes to SongBook 2026-07-31 15:56:27 +02:00
rudi 31006031f4 Method-name fix 2026-07-31 15:44:18 +02:00
rudi 8b9d47d000 Some Changes 2026-07-31 15:42:49 +02:00
rudi 67888e7f33 Testing the database
Tests der Datenbank hinzugefügt. Alle sind erfolgreich durchgelaufen.
2026-07-31 15:26:48 +02:00
rudi 38c3139403 Merge branch 'refactor/migration-to-prisma' of https://git.schamagusa.de/Schanbro/PsalmTafel into refactor/migration-to-prisma 2026-07-31 15:03:04 +02:00
rudi 3d1448c6aa Some tests and fixes (TODO fixes) 2026-07-31 14:58:40 +02:00
robin ff339fd8e8 Merge pull request 'refactor: updated deplay.yaml action' (#34) from small-fixes into main
Deploy Next.js via Docker / deploy (push) Successful in 39s
Reviewed-on: Schanbro/PsalmTafel#34
2026-07-31 12:43:58 +00:00
robin 63f0835f3b Merge branch 'main' into small-fixes 2026-07-31 12:43:49 +00:00
robin 65aae6af35 refactor: updated deplay.yaml action 2026-07-31 14:42:55 +02:00
robin 670c966868 Merge pull request 'Small fixes' (#33) from small-fixes into main
Deploy Next.js via Docker / deploy (push) Successful in 2m39s
Reviewed-on: Schanbro/PsalmTafel#33
2026-07-31 12:37:05 +00:00
robin e7e73d6882 update version number 2026-07-31 14:36:02 +02:00
robin d2488922e8 fix: fixed typo "talel" to "tafel" 2026-07-31 14:35:36 +02:00
rudi a81ea69a8a Added Statuscodes
Status Rückmeldungen den 'returns' hinzugefügt.
Schanbro/PsalmTafel#30
2026-07-31 13:57:05 +02:00
robin 6f15860beb style: move information screen to foreground 2026-07-31 12:49:37 +02:00
rudi 80d88608bd Editeted Doc
Dokumentation über den Funktionen angepasst
2026-07-31 11:56:10 +02:00
rudi 4380669fa3 Added status codes
Status Rückmeldungen den 'returns' hinzugefügt.
Schanbro/PsalmTafel#30
2026-07-31 11:51:08 +02:00
rudi aaedf3a71d Some changes 2026-07-31 11:47:14 +02:00
rudi 6be5cfb974 Added status to return
Status Rückmeldungen den 'returns' hinzugefügt.
Schanbro/PsalmTafel#30
2026-07-31 11:47:03 +02:00
rudi 9d8c7428e6 refactor: /api/songbooks 2026-07-31 11:25:18 +02:00
rudi 69378ca439 Some Route.js changes 2026-07-31 11:15:18 +02:00
rudi cb18b0e14f Added UpdateSongBook 2026-07-31 11:15:03 +02:00
rudi 389fd21975 Correct typo
CreateUser() -> createUser()
2026-07-31 11:14:44 +02:00
rudi d0890347dc AI comments cleanup 2026-07-31 10:46:35 +02:00
robin c28a5031f6 refactor: changed to rem 2026-07-30 10:48:34 +02:00
42 changed files with 4906 additions and 6000 deletions

No files matched your search

+13 -44
View File
@@ -20,43 +20,6 @@ jobs:
mv PsalmTafel/* . 2>/dev/null || mv psalmtafel/* . 2>/dev/null || mv */* . 2>/dev/null mv PsalmTafel/* . 2>/dev/null || mv psalmtafel/* . 2>/dev/null || mv */* . 2>/dev/null
rm repo.zip rm repo.zip
- name: Create tag in Gitea (based on package.json version)
run: |
apk add --no-cache jq curl
VERSION=$(jq -r '.version' package.json)
TAG="v${VERSION}"
echo "Tag: $TAG"
# Hole commit SHA von main (damit Tag korrekt gesetzt wird)
SHA=$(curl -s \
-H "Authorization: token ${{ secrets.GITEA_TOKEN }}" \
"http://172.17.0.1:3000/api/v1/repos/${{ github.repository }}/branches/main" \
| jq -r '.commit.id')
echo "main commit SHA: $SHA"
# Prüfen, ob Tag existiert
HTTP_STATUS=$(curl -s -o /dev/null -w "%{http_code}" \
-H "Authorization: token ${{ secrets.GITEA_TOKEN }}" \
"http://172.17.0.1:3000/api/v1/repos/${{ github.repository }}/repository/tags/${TAG}")
if [ "$HTTP_STATUS" -eq 404 ]; then
echo "Tag $TAG existiert nicht. Erstelle ihn..."
# Gitea: Tag erstellen via /git/refs
curl -X POST \
-H "Authorization: token ${{ secrets.GITEA_TOKEN }}" \
-H "Content-Type: application/json" \
-d "{
\"ref\": \"refs/tags/${TAG}\",
\"sha\": \"${SHA}\"
}" \
"http://172.17.0.1:3000/api/v1/repos/${{ github.repository }}/git/refs"
else
echo "Tag $TAG existiert bereits. Überspringe Erstellung."
fi
- name: Update Docker container - name: Update Docker container
run: | run: |
echo "Building new Next.js Docker image..." echo "Building new Next.js Docker image..."
@@ -79,20 +42,26 @@ jobs:
VERSION=$(jq -r '.version' package.json) VERSION=$(jq -r '.version' package.json)
echo "Current version: v$VERSION" echo "Current version: v$VERSION"
if [[ "$VERSION" == 0.* ]]; then # Shell-kompatible Prüfung (funktioniert zuverlässig in Alpine/sh)
IS_PRERELEASE=true case "$VERSION" in
echo "Version startet mit 0. -> Markiere als Prerelease." 0.*)
else IS_PRERELEASE="true"
IS_PRERELEASE=false echo "Version starts with 0. Setting prerelease to true."
echo "Version startet nicht mit 0. -> Normales Release." ;;
fi *)
IS_PRERELEASE="false"
echo "Setting prerelease to false."
;;
esac
# Prüfen, ob das Release bereits existiert
HTTP_STATUS=$(curl -s -o /dev/null -w "%{http_code}" \ HTTP_STATUS=$(curl -s -o /dev/null -w "%{http_code}" \
-H "Authorization: token ${{ secrets.GITEA_TOKEN }}" \ -H "Authorization: token ${{ secrets.GITEA_TOKEN }}" \
"http://172.17.0.1:3000/api/v1/repos/${{ github.repository }}/releases/tags/v$VERSION") "http://172.17.0.1:3000/api/v1/repos/${{ github.repository }}/releases/tags/v$VERSION")
if [ "$HTTP_STATUS" -eq 404 ]; then if [ "$HTTP_STATUS" -eq 404 ]; then
echo "Creating new release v$VERSION..." echo "Creating new release v$VERSION..."
# Gitea erstellt bei diesem Call automatisch auch den Tag v$VERSION auf 'main'
curl -X POST \ curl -X POST \
-H "Authorization: token ${{ secrets.GITEA_TOKEN }}" \ -H "Authorization: token ${{ secrets.GITEA_TOKEN }}" \
-H "Content-Type: application/json" \ -H "Content-Type: application/json" \
+1
View File
@@ -46,3 +46,4 @@ songs.sqlite
.gitignore .gitignore
/lib/generated/prisma /lib/generated/prisma
pnpm-lock.yaml
Binary file not shown.
+1 -1
View File
@@ -24,7 +24,7 @@ PsalmTafel is a real-time display system designed for choirs. It enables the cho
For detailed installation guides and deployment instructions, please visit our Wiki: For detailed installation guides and deployment instructions, please visit our Wiki:
* [PsalmTafel Wiki – Installation Guide](https://git.schamagusa.de/Schanbro/PsalmTafel/wiki/Installation) * [PsalmTafel Wiki – Installation Guide](https://psalmtafel.gem.schamagusa.de/wiki/installation)
--- ---
+2 -3
View File
@@ -2,7 +2,6 @@
import { error } from "console"; import { error } from "console";
import Papa from "papaparse"; import Papa from "papaparse";
import { addSongToSongbook } from "@/lib/db/managing";
interface CSVRow { interface CSVRow {
nummer: string; nummer: string;
@@ -31,8 +30,8 @@ export async function uploadCSVAction(formData:FormData) {
console.log("Data:", rows); console.log("Data:", rows);
rows.forEach(row => { rows.forEach(row => {
//console.log(`Nummer: ${row.number}, Titel: ${row.titel}`); console.log(`Nummer: ${row.nummer}, Titel: ${row.titel}`);
addSongToSongbook(String(row.titel), Number(songbookId), String(row.nummer)) //addSongToSongbook(String(row.titel), Number(songbookId), String(row.nummer))
}); });
return { success: true, message: `${rows.length} Zeilen erfolgreich importiert.`}; return { success: true, message: `${rows.length} Zeilen erfolgreich importiert.`};
+42 -31
View File
@@ -9,7 +9,7 @@ import { Screens } from "@/components/DatabaseOverview";
interface Songbook { interface Songbook {
id: number; id: number;
name: string; title: string;
language: string; language: string;
} }
@@ -22,7 +22,7 @@ interface Song {
interface SongInfo { interface SongInfo {
songbook_id: number; songbook_id: number;
songbook_name: string; songbook_title: string;
song_number: string; song_number: string;
title: string; title: string;
} }
@@ -34,7 +34,7 @@ export default function AdminPage() {
const [number, setNumber] = useState(""); const [number, setNumber] = useState("");
const [title, setTitle] = useState(""); const [title, setTitle] = useState("");
const [newBookName, setNewBookName] = useState(""); const [newBookTitle, setNewBookTitle] = useState("");
const [newBookLanguage, setNewBookLanguage] = useState(""); const [newBookLanguage, setNewBookLanguage] = useState("");
const [uploadStatus, setUploadStatus] = useState<string | null>(null); const [uploadStatus, setUploadStatus] = useState<string | null>(null);
@@ -96,21 +96,34 @@ export default function AdminPage() {
} }
try { try {
const res = await fetch("/api/songs", { // Create song
const res1 = await fetch("/api/songs", {
method: "POST", method: "POST",
headers: { "Content-Type": "application/json" }, headers: { "Content-Type": "application/json" },
body: JSON.stringify({ body: JSON.stringify({
songbookId: Number(selectedSongbookId),
number: number,
title: title title: title
}) })
}); })
if (res.ok) { if (res1.ok) {
alert("Lied erfolgreich hinzugefügt!"); console.log("Lied erfolgreich erstellt!");
setNumber("");
setTitle("");
} else { } 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) { } catch (error) {
console.error("Failed sending current songID:", error); console.error("Failed sending current songID:", error);
@@ -124,19 +137,17 @@ export default function AdminPage() {
} }
try { try {
const res = await fetch("/api/songs/attach", { const res2 = await fetch(`/api/songbooks/${Number(selectedSongbookId)}/songs/${selectedSong.song_id}`, {
method: "POST", method: "POST",
headers: { "Content-Type": "application/json" }, headers: { "Content-Type": "application/json" },
body: JSON.stringify({ body: JSON.stringify({
songbookId: selectedSongbookId, number: number
songId: selectedSong.song_id,
number: number,
}) })
}); })
if (res.ok) { if (res2.ok) {
alert("Lied erfolgreich zum Liederbuch hinzugefügt!"); console.log("Lied erfolgreich dem Liederbuch zugewiesen!");
} else { } else {
alert("Fehler beim Senden."); console.log("Fehler");
} }
} catch (error) { } catch (error) {
console.error("Failed sending current songID:", error); console.error("Failed sending current songID:", error);
@@ -169,8 +180,8 @@ export default function AdminPage() {
} }
const addSongbook = async () => { const addSongbook = async () => {
if (!newBookName) { if (!newBookTitle) {
alert("Der Name des Liederbuches darf nicht leer sein!"); alert("Der Title des Liederbuches darf nicht leer sein!");
return; return;
} }
@@ -178,14 +189,14 @@ export default function AdminPage() {
const res = await fetch("/api/songbooks", { const res = await fetch("/api/songbooks", {
method: "POST", method: "POST",
headers: { "Content-Type": "application/json" }, headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name: newBookName, language: newBookLanguage }) body: JSON.stringify({ title: newBookTitle, language: newBookLanguage })
}); });
if (res.ok) { if (res.ok) {
const createdBook = await res.json(); const createdBook = await res.json();
setSongbooks([...songbooks, createdBook]); setSongbooks([...songbooks, createdBook]);
alert("Liederbuch erfolgreich erstellt!"); alert("Liederbuch erfolgreich erstellt!");
setNewBookName(""); setNewBookTitle("");
setNewBookLanguage(""); setNewBookLanguage("");
} else { } else {
alert("Failed adding songbook!"); alert("Failed adding songbook!");
@@ -215,8 +226,8 @@ export default function AdminPage() {
<Input.Text <Input.Text
type="text" type="text"
placeholder="z.B. Gesangbuch" placeholder="z.B. Gesangbuch"
value={newBookName} value={newBookTitle}
onChange={(e) => setNewBookName(e.target.value)} onChange={(e) => setNewBookTitle(e.target.value)}
/> />
</div> </div>
<div> <div>
@@ -248,7 +259,7 @@ export default function AdminPage() {
<option value="">-- Bitte wählen --</option> <option value="">-- Bitte wählen --</option>
{songbooks.map((book) => ( {songbooks.map((book) => (
<option key={book.id} value={String(book.id)}> <option key={book.id} value={String(book.id)}>
{book.name}{book.language ? ` (${book.language})` : ""} {book.title}{book.language ? ` (${book.language})` : ""}
</option> </option>
))} ))}
</Input.Select> </Input.Select>
@@ -290,7 +301,7 @@ export default function AdminPage() {
<option value="">-- Bitte wählen --</option> <option value="">-- Bitte wählen --</option>
{songbooks.map((book) => ( {songbooks.map((book) => (
<option key={book.id} value={String(book.id)}> <option key={book.id} value={String(book.id)}>
{book.name}{book.language ? ` (${book.language})` : ""} {book.title}{book.language ? ` (${book.language})` : ""}
</option> </option>
))} ))}
</Input.Select> </Input.Select>
@@ -335,7 +346,7 @@ export default function AdminPage() {
<ul className="list-disc list-inside pl-2 text-xs text-neutral-400"> <ul className="list-disc list-inside pl-2 text-xs text-neutral-400">
{songInfos.map((info) => ( {songInfos.map((info) => (
<li key={info.songbook_id}> <li key={info.songbook_id}>
{info.songbook_name} (Nr. {info.song_number}) {info.songbook_title} (Nr. {info.song_number})
</li> </li>
))} ))}
</ul> </ul>
@@ -356,7 +367,7 @@ export default function AdminPage() {
<option value="">-- Bitte wählen --</option> <option value="">-- Bitte wählen --</option>
{songbooks.map((book) => ( {songbooks.map((book) => (
<option key={book.id} value={String(book.id)}> <option key={book.id} value={String(book.id)}>
{book.name}{book.language ? ` (${book.language})` : ""} {book.title}{book.language ? ` (${book.language})` : ""}
</option> </option>
))} ))}
</Input.Select> </Input.Select>
@@ -390,7 +401,7 @@ export default function AdminPage() {
{songInfos.length > 0 ? ( {songInfos.length > 0 ? (
songInfos.map((info) => ( songInfos.map((info) => (
<option key={info.songbook_id} value={String(info.songbook_id)}> <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> </option>
)) ))
): ""} ): ""}
+146
View File
@@ -0,0 +1,146 @@
import { NextResponse } from "next/server";
import { getSongBookById, updateSongBook, deleteSongBook } from "@/lib/db/songbook";
// import { parseInt } from "@/lib/helper/checkvar";
/**
* @openapi
* /api/songbooks/{id}:
* get:
* summary: Einzelnen Songbook abrufen
* tags:
* - Songbooks
* parameters:
* - in: path
* name: id
* required: true
* schema:
* type: integer
* description: Die ID des Songbooks
* responses:
* 200:
* description: Songbook erfolgreich gefunden
* 400:
* description: Ungültige Songbook-ID
* 404:
* description: Songbook nicht gefunden
* 500:
* description: Serverfehler
*/
export async function GET(request: Request, { params }) {
try {
const { songBookId } = await params;
const res = await getSongBookById(songBookId);
if (!res.success) {
return NextResponse.json({ message: res.error }, { status: res.status });
}
return NextResponse.json(res.songBook, { status: res.status });
} catch (error) {
console.error("API Error:", error);
return NextResponse.json(
{ error: "Fehler beim Laden der Songbookinfos" },
{ status: 500 }
);
}
}
/**
* @openapi
* /api/songbooks/{id}:
* patch:
* summary: Songbook aktualisieren
* tags:
* - Songbooks
* parameters:
* - in: path
* name: id
* required: true
* schema:
* type: integer
* description: Die ID des Songbooks
* requestBody:
* required: true
* content:
* application/json:
* schema:
* type: object
* responses:
* 200:
* description: Songbook erfolgreich aktualisiert
* 400:
* description: Ungültige Parameter oder Daten
* 404:
* description: Songbook nicht gefunden
* 500:
* description: Serverfehler
*/
export async function PATCH(request: Request, { params }) {
try {
const { songBookId } = await params;
const data = await request.json();
const res = await updateSongBook(songBookId, data);
if (!res.success) {
return NextResponse.json({ message: res.error }, { status: res.status });
}
return NextResponse.json(res.songBook, { status: res.status });
} catch (error) {
console.error("API Error:", error);
return NextResponse.json(
{ error: "Fehler beim Laden der Songbookinfos" },
{ status: 500 }
);
}
}
/**
* @openapi
* /api/songbooks/{id}:
* delete:
* summary: Songbook löschen
* tags:
* - Songbooks
* parameters:
* - in: path
* name: id
* required: true
* schema:
* type: integer
* description: Die ID des Songbooks
* responses:
* 200:
* description: Songbook erfolgreich gelöscht
* 400:
* description: Ungültige Songbook-ID
* 404:
* description: Songbook nicht gefunden
* 500:
* description: Serverfehler
*/
export async function DELETE(request: Request, { params }) {
try {
const { songBookId } = await params;
const res = await deleteSongBook(songBookId);
if (!res.success) {
return NextResponse.json({ message: res.error }, { status: res.status });
}
return NextResponse.json(res.songBook, { status: res.status });
} catch (error) {
console.error("API Error:", error);
return NextResponse.json(
{ error: "Fehler beim Laden der Songbookinfos" },
{ status: 500 }
);
}
}
@@ -0,0 +1,186 @@
import { NextResponse } from "next/server";
import { addSongToBook, updateSongInBook, removeSongFromBook } from "@/lib/db/songbooksongs";
// import { parseInt } from "@/lib/helper/checkvar";
/**
* @openapi
* /api/songbooks/{songBookId}/songs/{songId}:
* post:
* summary: Song zu Liederbuch hinzufügen
* tags:
* - Songbook
* parameters:
* - in: path
* name: songBookId
* required: true
* schema:
* type: integer
* description: Die ID des Liederbuchs
* - in: path
* name: songId
* required: true
* schema:
* type: integer
* description: Die ID des Songs
* requestBody:
* required: true
* content:
* application/json:
* schema:
* type: object
* required:
* - number
* properties:
* number:
* type: string
* example: "104a"
* description: Die Songnummer im Liederbuch
* responses:
* 200:
* description: Song erfolgreich zugewiesen
* 400:
* description: Ungültige Parameter oder fehlende Songnummer
* 409:
* description: Songnummer bereits vergeben oder Song existiert bereits im Buch
* 500:
* description: Serverfehler
*/
export async function POST(request: Request, { params }) {
try {
const { songBookId, songId } = await params;
const data = await request.json();
const res = await addSongToBook(songId, songBookId, data.number);
if (!res.success) {
return NextResponse.json({ message: res.error }, { status: res.status });
}
return NextResponse.json(res.entry, { status: res.status });
} catch (error) {
console.error("API Error:", error);
return NextResponse.json(
{ error: "Fehler beim Laden der Songbookinfos" },
{ status: 500 }
);
}
}
/**
* @openapi
* /api/songbooks/{songBookId}/songs/{songId}:
* patch:
* summary: Songnummer eines Songs im Liederbuch aktualisieren
* tags:
* - Songbook
* parameters:
* - in: path
* name: songBookId
* required: true
* schema:
* type: integer
* description: Die ID des Liederbuchs
* - in: path
* name: songId
* required: true
* schema:
* type: integer
* description: Die ID des Songs
* requestBody:
* required: true
* content:
* application/json:
* schema:
* type: object
* required:
* - number
* properties:
* number:
* type: string
* example: "105"
* description: Die neue Songnummer im Liederbuch
* responses:
* 200:
* description: Songnummer erfolgreich aktualisiert
* 400:
* description: Ungültige Parameter oder fehlende Daten
* 404:
* description: Zuweisung nicht gefunden
* 409:
* description: Neue Songnummer bereits vergeben
* 500:
* description: Serverfehler
*/
export async function PATCH(request: Request, { params }) {
try {
const { songBookId, songId } = await params;
const data = await request.json();
const res = await updateSongInBook(songId, songBookId, data);
if (!res.success) {
return NextResponse.json({ message: res.error }, { status: res.status });
}
return NextResponse.json(res.entry, { status: res.status });
} catch (error) {
console.error("API Error:", error);
return NextResponse.json(
{ error: "Fehler beim Laden der Songbookinfos" },
{ status: 500 }
);
}
}
/**
* @openapi
* /api/songbooks/{songBookId}/songs/{songId}:
* delete:
* summary: Song aus Liederbuch entfernen
* tags:
* - Songbook
* parameters:
* - in: path
* name: songBookId
* required: true
* schema:
* type: integer
* description: Die ID des Liederbuchs
* - in: path
* name: songId
* required: true
* schema:
* type: integer
* description: Die ID des Songs
* responses:
* 200:
* description: Song erfolgreich aus dem Liederbuch entfernt
* 400:
* description: Ungültige Parameter
* 404:
* description: Zuweisung nicht gefunden
* 500:
* description: Serverfehler
*/
export async function DELETE(request: Request, { params }) {
try {
const { songBookId, songId } = await params;
const res = await removeSongFromBook(songId, songBookId);
if (!res.success) {
return NextResponse.json({ message: res.error }, { status: res.status });
}
return NextResponse.json(res.entry, { status: res.status });
} catch (error) {
console.error("API Error:", error);
return NextResponse.json(
{ error: "Fehler beim Laden der Songbookinfos" },
{ status: 500 }
);
}
}
@@ -0,0 +1,53 @@
import { NextResponse } from "next/server";
import { getSongByNumber } from "@/lib/db/songbooksongs";
/**
* @openapi
* /api/songbooks/{id}/songs:
* get:
* summary: Einen Song nach Nummer in einem Songbook suchen
* tags:
* - Songbook
* parameters:
* - in: path
* name: id
* required: true
* schema:
* type: integer
* description: Die ID des Songbooks
* responses:
* 200:
* description: Songbook erfolgreich gefunden
* 400:
* description: Ungültige Songbook-ID
* 404:
* description: Songbook nicht gefunden
* 500:
* description: Serverfehler
*/
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(songBookId, number);
if (!res.success) {
return NextResponse.json({ message: res.error }, { status: res.status });
}
return NextResponse.json(res.entry, { status: res.status });
}
return NextResponse.json({ message: "Need a number query (number=123)" }, { status: 400 });
} catch (error) {
console.error("API Error:", error);
return NextResponse.json(
{ error: "Fehler beim Laden der Songbookinfos" },
{ status: 500 }
);
}
}
+128 -16
View File
@@ -1,27 +1,139 @@
// @wikiCategory: Liederbücher
import { NextResponse } from "next/server"; import { NextResponse } from "next/server";
import { getSongbooks, addSongbook } from "@/lib/db/managing"; import { getSongBooks, searchSongBooksByTitle, createSongBook } from "@/lib/db/songbook";
export async function GET() {
/**
* @openapi
* /api/songbooks:
* get:
* summary: Get all songbooks
* responses:
* 200:
* description: List of songbooks
* 500:
* description: Internal Server Error
*
* @wikiDescription: Liste aller Liederbücher abrufen
*/
export async function GET(request: Request) {
try { try {
const songbooks = await getSongbooks(); const { searchParams } = new URL(request.url);
return NextResponse.json(songbooks); const query = searchParams.get("query") || searchParams.get("q");
} catch (error) {
return NextResponse.json({ success: false, message: error}, { status: 500})
}
}
export async function POST(request: Request) {
try {
const { name, language } = await request.json();
if (!name ) {
return NextResponse.json({ success: false, message: "Fields incomplete (name)"}, { status: 400 }) // Wenn ein Suchbegriff übergeben wurde -> Sucheinbindung
if (query) {
const res = await searchSongBooksByTitle(query); // You can enter a limit
if (!res.success) {
return NextResponse.json({ message: res.error }, { status: res.status });
}
return NextResponse.json(res.songBooks, { status: res.status });
} }
const newBook = await addSongbook(String(name), String(language)) // Ansonsten alle Bücher abrufen
const res = await getSongBooks();
if (!res.success) {
return NextResponse.json({ message: res.error }, { status: res.status });
}
return NextResponse.json(res.songBooks, { status: res.status });
return NextResponse.json(newBook, { status: 201 })
} catch (error) { } catch (error) {
return NextResponse.json({ success: false }, { status: 500 }) console.error("GET /api/songbooks error:", error);
return NextResponse.json(
{ message: "Internal Server Error" },
{ status: 500 }
);
}
}
/**
* @openapi
* /api/songbooks:
* post:
* summary: Creates a new songbook
* requestBody:
* required: true
* content:
* application/json:
* schema:
* type: object
* required:
* - title
* properties:
* title:
* type: string
* example: "Feiert Jesus 1"
* language:
* type: string
* example: "DE"
* responses:
* 201:
* description: Songbook successfully created
* content:
* application/json:
* schema:
* type: object
* properties:
* success:
* type: boolean
* example: true
* 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)
* 409:
* description: Conflict (title already exists)
* 500:
* description: Internal Server Error
*
* @wikiDescription: Neues Liederbuch erstellen
*/
export async function POST(request: Request) {
try {
const data = await request.json();
if (!data.title || !data.language) {
return NextResponse.json(
{ message: "Field 'title' and 'language' are required" },
{ status: 400 }
);
}
const res = await createSongBook(data);
if (!res.success) {
return NextResponse.json(
{ message: res.error },
{ status: res.status }
);
}
return NextResponse.json(res, { status: res.status });
} catch (error) {
console.error("POST /api/songbooks error:", error);
return NextResponse.json(
{ message: "Internal Server Error" },
{ status: 500 }
);
} }
} }
-20
View File
@@ -1,20 +0,0 @@
import { NextResponse } from "next/server";
import { getSongInfos } from "@/lib/db/managing";
export async function GET(
request: Request,
{ params }: { params: Promise<{ id: string }> }
) {
try {
const { id } = await params;
const songInfos = await getSongInfos(id);
return NextResponse.json(songInfos || []);
} catch (error) {
console.error("API Error:", error);
return NextResponse.json(
{ error: "Fehler beim Laden der Songinfos" },
{ status: 500 }
);
}
}
+142
View File
@@ -0,0 +1,142 @@
import { NextResponse } from "next/server";
import { getSongById, updateSong, deleteSong } from "@/lib/db/song";
// import { parseInt } from "@/lib/helper/checkvar";
/**
* @openapi
* /api/songs/{id}:
* get:
* summary: Einzelnen Song abrufen
* tags:
* - Songs
* parameters:
* - in: path
* name: id
* required: true
* schema:
* type: integer
* description: Die ID des Songs
* responses:
* 200:
* description: Song erfolgreich gefunden
* 400:
* description: Ungültige Song-ID
* 404:
* description: Song nicht gefunden
* 500:
* description: Serverfehler
*/
export async function GET(request: Request, { params }) {
try {
const { songId } = await params;
const res = await getSongById(songId);
if (!res.success) {
return NextResponse.json({ message: res.error }, { status: res.status });
}
return NextResponse.json(res.song, { status: res.status });
} catch (error) {
console.error("API Error:", error);
return NextResponse.json(
{ error: "Fehler beim Laden der Songinfos" },
{ status: 500 }
);
}
}
/**
* @openapi
* /api/songs/{id}:
* patch:
* summary: Song aktualisieren
* tags:
* - Songs
* parameters:
* - in: path
* name: id
* required: true
* schema:
* type: integer
* description: Die ID des Songs
* requestBody:
* required: true
* content:
* application/json:
* schema:
* type: object
* responses:
* 200:
* description: Song erfolgreich aktualisiert
* 400:
* description: Ungültige Parameter oder Daten
* 404:
* description: Song nicht gefunden
* 500:
* description: Serverfehler
*/
export async function PATCH(request: Request, { params }) {
try {
const { songId } = await params;
const data = await request.json();
const res = await updateSong(songId, data);
if (!res.success) {
return NextResponse.json({ message: res.error }, { status: res.status });
}
return NextResponse.json(res.song, { status: res.status });
} catch (error) {
console.error("API Error:", error);
return NextResponse.json(
{ error: "Fehler beim Laden der Songinfos" },
{ status: 500 }
);
}
}
/**
* @openapi
* /api/songs/{id}:
* delete:
* summary: Song löschen
* tags:
* - Songs
* parameters:
* - in: path
* name: id
* required: true
* schema:
* type: integer
* description: Die ID des Songs
* responses:
* 200:
* description: Song erfolgreich gelöscht
* 400:
* description: Ungültige Song-ID
* 404:
* description: Song nicht gefunden
* 500:
* description: Serverfehler
*/
export async function DELETE(request: Request, { params }) {
try {
const { songId } = await params;
const res = await deleteSong(songId);
if (!res.success) {
return NextResponse.json({ message: res.error }, { status: res.status });
}
return NextResponse.json(res.song, { status: res.status });
} catch (error) {
console.error("API Error:", error);
return NextResponse.json(
{ error: "Fehler beim Laden der Songinfos" },
{ status: 500 }
);
}
}
-40
View File
@@ -1,40 +0,0 @@
import { NextResponse } from "next/server";
import { attachSongToSongbook } from "@/lib/db/managing";
export async function POST(request: Request) {
try {
const body = await request.json();
const { songId, songbookId, number } = body;
if (isNaN(songId) || isNaN(songbookId) || !number) {
return NextResponse.json(
{ error: "Ungültige IDs oder fehlende Nummer." },
{ status: 400 }
);
}
const result = await attachSongToSongbook(
Number(songId),
Number(songbookId),
String(number)
);
if (result.success) {
return NextResponse.json(
{ message: "Lied erfolgreich verknüpft!" },
{ status: 200 }
);
} else {
return NextResponse.json(
{ error: "Fehler beim Verknüpfen in der Datenbank." },
{ status: 500 }
);
}
} catch (error) {
console.error("API Error in /api/songs/attach:", error);
return NextResponse.json(
{ error: "Ungültiges JSON oder Serverfehler." },
{ status: 500 }
);
}
}
-39
View File
@@ -1,39 +0,0 @@
import { NextResponse } from "next/server";
import { removeSongfromSongbook } from "@/lib/db/managing";
export async function POST(request: Request) {
try {
const body = await request.json();
const { songId, songbookId } = body;
if (isNaN(songId) || isNaN(songbookId)) {
return NextResponse.json(
{ error: "Ungültige IDs." },
{ status: 400 }
);
}
const result = await removeSongfromSongbook(
Number(songId),
Number(songbookId)
);
if (result.success) {
return NextResponse.json(
{ message: "Lied erfolgreich aus dem Liederbuch gelöscht!" },
{ status: 200 }
);
} else {
return NextResponse.json(
{ error: "Fehler beim Löschen aus dem Liederbuch." },
{ status: 500 }
);
}
} catch (error) {
console.error("API Error in /api/songs/remove:", error);
return NextResponse.json(
{ error: "Ungültiges JSON oder Serverfehler." },
{ status: 500 }
);
}
}
+118 -19
View File
@@ -1,31 +1,130 @@
// @wikiCategory: Lieder
import { NextResponse } from "next/server"; import { NextResponse } from "next/server";
import { getSongs, searchSongsByTitle, createSong, } from "@/lib/db/song";
import { getSongs, addSongToSongbook } from "@/lib/db/managing";
export async function GET() {
const songs = await getSongs(); /**
if (songs) { * @openapi
return NextResponse.json(songs); * /api/songs:
} else { * get:
return NextResponse.json({ success: false}, { status: 500}) * summary: Get all songs
} * responses:
} * 200:
export async function POST(request: Request) { * description: List of songs
* 500:
* description: Internal Server Error
*/
export async function GET(request: Request) {
try { try {
const { title, songbookId, number } = await request.json(); const { searchParams } = new URL(request.url);
const query = searchParams.get("query") || searchParams.get("q");
if (!title || !songbookId || !number) {
return NextResponse.json({ success: false, message: "Fields incomplete"}, { status: 400 }); if (query) {
const res = await searchSongsByTitle(query/*, 20*/); // You can enter a limit (default: 20)
if (!res.success) {
return NextResponse.json({ message: res.error }, { status: res.status });
}
return NextResponse.json(res.songBooks, { status: res.status });
} }
const result = await addSongToSongbook(title, Number(songbookId), String(number)); // Ansonsten alle Songs abrufen
if (result.success) { const res = await getSongs();
return NextResponse.json({ success: true });
} else { if (!res.success) {
return NextResponse.json({ success: false }, { status: 500 }); return NextResponse.json({ message: res.error }, { status: res.status });
} }
return NextResponse.json(res.songs, { status: res.status });
} catch (error) { } catch (error) {
return NextResponse.json({ success: false }, { status: 500 }); console.error("POST /api/songs error:", error);
return NextResponse.json(
{ message: "Internal Server Error" },
{ status: 500 }
);
}
}
/**
* @openapi
* /api/songs:
* post:
* summary: Creates a new song
* requestBody:
* required: true
* content:
* application/json:
* schema:
* type: object
* required:
* - name
* properties:
* name:
* type: string
* example: "Großer Gott"
* responses:
* 201:
* description: Songbook successfully created
* content:
* application/json:
* schema:
* type: object
* properties:
* success:
* type: boolean
* example: true
* songBook:
* type: object
* properties:
* id:
* type: integer
* example: 1
* title:
* type: string
* example: "Großer Gott"
* 400:
* description: Bad Request (missing name)
* 409:
* description: Conflict (title already exists)
* 500:
* description: Internal Server Error
*/
export async function POST(request: Request) {
try {
const data = await request.json();
if (!data.title) {
return NextResponse.json(
{ message: "Field 'title' is required"},
{ status: 400 }
);
}
const res = await createSong(data);
if (!res.success) {
return NextResponse.json(
{
message: res.error,
song: res.song
},
{ status: res.status }
);
}
return NextResponse.json(res, { status: res.status });
} catch (error) {
console.error("POST /api/songs error:", error);
return NextResponse.json(
{ message: "Internal Server Error" },
{ status: 500 }
);
} }
} }
+44 -15
View File
@@ -1,5 +1,7 @@
// @wikiCategory: Stream
import { NextResponse } from "next/server"; import { NextResponse } from "next/server";
import { getSong } from "@/lib/db/managing"; import { getSongById } from "@/lib/db/song";
let currentSong = { let currentSong = {
songID: "", songID: "",
@@ -8,30 +10,52 @@ let currentSong = {
title: "" title: ""
}; };
// @wikiDescription: Akutell gestreamtes Lied abrufen
export async function GET() { export async function GET() {
return NextResponse.json(currentSong) return NextResponse.json(currentSong)
} }
// @wikiDescription: Lied zum Streamen festlegen
export async function POST(request: Request) { export async function POST(request: Request) {
try { try {
const data = await request.json(); const data = await request.json();
const songID = data.songID; const { songID, songbookID } = data;
const songbookID = data.songbookID;
if (!songID || !songbookID) { if (!songID || !songbookID) {
return NextResponse.json({ success: false, error: "Fields incomplete!" }, { status: 400 }); return NextResponse.json(
{ success: false, error: "Fields incomplete!" },
{ status: 400 }
);
} }
const song = await getSong(Number(songbookID), String(songID)); const result = await getSongById(songID);
if (song) { if (result.success && result.song) {
currentSong = { const song = result.song;
songID: String(songID),
songbook: song.songbook_name, // looking for the songbook with matching ID
number: song.number, const matchedBook = song.songBooks.find(
title: song.song_title, (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 { } else {
// song does not exist
currentSong = { currentSong = {
songID: "", songID: "",
songbook: "", songbook: "",
@@ -39,10 +63,15 @@ export async function POST(request: Request) {
title: "", title: "",
}; };
} }
console.log(currentSong);
return NextResponse.json({ success: true }); console.log("Aktualisierter currentSong:", currentSong);
return NextResponse.json({ success: true, currentSong });
} catch (error) { } catch (error) {
return NextResponse.json({ success: false, error: "Server-Fehler" }, { status: 500 }); console.error("API POST Error:", error);
return NextResponse.json(
{ success: false, error: "Server-Fehler" },
{ status: 500 }
);
} }
} }
+127
View File
@@ -29,3 +29,130 @@ section {
margin-bottom: 50px; margin-bottom: 50px;
} }
h1 {
font-size: 2rem;
}
/* Shiki Code-Blöcke stylen */
pre {
padding: 1rem;
border-radius: 0.75rem;
border: 1px solid #27272a; /* Tailwind zinc-800 */
overflow-x: auto;
font-size: 0.875rem;
}
pre code {
background-color: transparent !important;
padding: 0 !important;
border: none !important;
}
/* Shiki / Rehype Pretty Code Block Container */
figure[data-rehype-pretty-code-figure] {
margin-top: 1.5rem;
margin-bottom: 1.5rem;
border-radius: 0.75rem;
overflow: hidden;
border: 1px solid #27272a; /* Tailwind zinc-800 */
background-color: #0d1117; /* Dunkler VS-Code Hintergrund */
}
/* Der Titel/Dateiname (falls im MDX angegeben) */
div[data-rehype-pretty-code-title] {
background-color: #161b22;
border-bottom: 1px solid #27272a;
padding: 0.5rem 1rem;
font-family: monospace;
font-size: 0.75rem;
color: #8b949e;
}
/* Der eigentliche Code-Bereich */
figure[data-rehype-pretty-code-figure] pre {
margin: 0 !important;
padding: 1rem !important;
background-color: transparent !important;
overflow-x: auto;
font-size: 0.875rem;
line-height: 1.7;
}
figure[data-rehype-pretty-code-figure] code {
font-family: var(--font-mono, monospace);
}
/* Container für den Code-Block */
/* Container für den Code-Block */
figure[data-rehype-pretty-code-figure] {
position: relative;
margin-top: 1.5rem;
margin-bottom: 1.5rem;
border-radius: 0.75rem;
overflow: hidden;
border: 1px solid #27272a;
background-color: #0d1117;
}
/* Leeres Pseudo-Element der Figure deaktivieren */
figure[data-rehype-pretty-code-figure]::before {
display: none !important;
}
/* Sprach-Badge links oben */
figure[data-rehype-pretty-code-figure] pre[data-language]::before {
content: attr(data-language);
display: block !important;
position: absolute;
top: 0.6rem;
left: 0.5rem;
font-family: var(--font-mono, ui-monospace, monospace);
font-size: 0.68rem;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.05em;
color: #a1a1aa;
background-color: #18181b;
border: 1px solid #27272a;
padding: 0.15rem 0.5rem;
border-radius: 0.375rem;
pointer-events: none;
z-index: 10;
}
/* Platz oben im Code-Block */
figure[data-rehype-pretty-code-figure] pre {
margin: 0 !important;
padding: 1rem !important;
padding-top: 2.6rem !important; /* Platz für Badge & Button */
background-color: transparent !important;
overflow-x: auto;
font-size: 0.875rem;
line-height: 1.7;
}
h1, h2, h3, h4, h5, h6 {
scroll-margin-top: 5rem; /* <-- Höhe deines Headers + etwas Abstand */
}
html {
scroll-behavior: smooth;
}
/* Anchor-Link Styling */
.heading-anchor {
opacity: 0;
margin-right: 1em; /* Abstand zum nachfolgenden Text */
color: #3b82f6; /* Tailwind blue-500 */
text-decoration: none;
font-weight: 800;
transition: opacity 0.15s ease-in-out;
}
h1:hover .heading-anchor,
h2:hover .heading-anchor,
h3:hover .heading-anchor,
h4:hover .heading-anchor,
.heading-anchor:focus {
opacity: 1;
}
+111 -16
View File
@@ -3,11 +3,65 @@
import { useState, useEffect } from "react"; import { useState, useEffect } from "react";
export default function SenderPage() { export default function SenderPage() {
const [isFullscreen, setIsFullscreen] = useState(false);
const [songID, setSongID] = useState(""); const [songID, setSongID] = useState("");
const [songbook, setSongbook] = useState(""); const [songbook, setSongbook] = useState("");
const [number, setNumber] = useState(""); const [number, setNumber] = useState("");
const [title, setTitle] = useState(""); const [title, setTitle] = useState("");
// --- Screen Wake Lock API Integration ---
useEffect(() => {
let wakeLock: WakeLockSentinel | null = null;
const requestWakeLock = async () => {
try {
if ("wakeLock" in navigator) {
wakeLock = await navigator.wakeLock.request("screen");
}
} catch (err) {
console.error("Wake Lock Fehler:", err);
}
};
requestWakeLock();
// Erneutes Anfordern, falls der Tab/die App gewechselt wurde
const handleVisibilityChange = () => {
if (document.visibilityState === "visible") {
requestWakeLock();
}
};
document.addEventListener("visibilitychange", handleVisibilityChange);
return () => {
document.removeEventListener("visibilitychange", handleVisibilityChange);
if (wakeLock) {
wakeLock.release();
}
};
}, []);
// --- Fullscreen Steuerung ---
const toggleFullscreen = () => {
if (!document.fullscreenElement) {
document.documentElement
.requestFullscreen()
.then(() => {
setIsFullscreen(true);
})
.catch((err) => {
console.error("Vollbild fehlgeschlagen:", err);
});
} else {
document.exitFullscreen().then(() => {
setIsFullscreen(false);
});
}
};
// --- Daten abrufen ---
const getID = async () => { const getID = async () => {
try { try {
const res = await fetch("/api/stream/currentID"); const res = await fetch("/api/stream/currentID");
@@ -28,22 +82,63 @@ export default function SenderPage() {
}, []); }, []);
return ( return (
<div className="flex h-screen w-screen flex-col items-center justify-between bg-black text-white font-sans select-none overflow-hidden"> <div
<div className="w-full text-center py-2"> className={`absolute top-0 left-0 z-50 flex h-screen w-screen flex-col items-center justify-between bg-black text-white select-none overflow-hidden p-2`}
<span className="text-[7rem] md:text-[11rem] font-black uppercase block leading-none"> >
{songbook} {/* 1. Liederbuch */}
</span> <header className="w-full flex-[1.5] flex items-center justify-center overflow-hidden py-1">
</div> <svg viewBox="0 0 1000 200" className="w-full h-full max-h-full">
<div className="flex-1 flex items-center justify-center w-full"> <text
<h1 className="text-[14rem] md:text-[20rem] font-black leading-none tracking-tighter text-white"> x="50%"
{number} y="50%"
</h1> dominantBaseline="central"
</div> textAnchor="middle"
<div className="w-full text-center pb-2 px-4"> className="fill-amber-300 font-black uppercase"
<p className="text-3xl md:text-6xl font-medium text-neutral-400 truncate"> fontSize="220"
{title} >
</p> {songbook}
</div> </text>
</svg>
</header>
{/* 2. Nummer */}
<main className="w-full flex-[5] flex items-center justify-center overflow-hidden py-1">
<svg viewBox="0 0 1000 500" className="w-full h-full max-h-full">
<text
x="50%"
y="50%"
dominantBaseline="central"
textAnchor="middle"
className="fill-white font-black"
fontSize="520"
>
{number}
</text>
</svg>
</main>
{/* 3. Titel */}
<footer className="w-full flex-[1] flex items-center justify-center overflow-hidden py-1">
<svg viewBox="0 0 1000 120" className="w-full h-full max-h-full">
<text
x="50%"
y="50%"
dominantBaseline="central"
textAnchor="middle"
className="fill-zinc-200 font-semibold"
fontSize="90"
>
{title}
</text>
</svg>
</footer>
<button
onClick={toggleFullscreen}
className="fixed top-4 right-4 z-50 bg-neutral-800 hover:bg-neutral-700 text-white px-4 py-2 rounded-lg opacity-40 hover:opacity-100 transition-opacity"
>
{isFullscreen ? "Vollbild beenden" : "Vollbild starten"}
</button>
</div> </div>
); );
} }
+93
View File
@@ -0,0 +1,93 @@
import { getWikiPageBySlug } from '@/lib/wiki';
import { notFound } from 'next/navigation';
import { MDXRemote } from 'next-mdx-remote/rsc';
import rehypePrettyCode from 'rehype-pretty-code';
import rehypeSlug from 'rehype-slug';
import rehypeAutolinkHeadings from 'rehype-autolink-headings';
import { Callout, Grid, Card, Steps, Step, InlineCode, CodeBlockContainer, API } from '@/components/mdx-components';
import Article from '@/components/wiki/Article';
const mdxOptions = {
mdxOptions: {
rehypePlugins: [
rehypeSlug, // creates heading-ids automaticly
[
rehypeAutolinkHeadings,
{
behavior: 'prepend', // symbol is PRE header
properties: {
className: ['heading-anchor'],
ariaHidden: 'true',
tabIndex: -1,
},
content: {
type: 'text',
value: ' #', // symbol
},
},
],
[
rehypePrettyCode,
{
theme: 'github-dark',
keepBackground: true,
},
],
],
},
};
const mdxComponents = {
// Eigene UI-Komponenten
Callout,
Grid,
Card,
Steps,
Step,
API,
// Custom Typography Überschreibungen
code: InlineCode,
pre: CodeBlockContainer,
h1: (props: any) => <h1 className="text-3xl font-bold text-white mt-8 mb-4 border-b border-zinc-800 pb-3" {...props} />,
h2: (props: any) => <h2 className="text-2xl font-bold text-white mt-10 mb-4" {...props} />,
h3: (props: any) => <h3 className="text-xl font-semibold text-white mt-6 mb-3" {...props} />,
};
type PageProps = {
params: Promise<{
slug: string;
}>;
};
export default async function Page({ params }: PageProps) {
const { slug } = await params;
const article = await getWikiPageBySlug(slug);
if (!article) {
notFound();
}
return (
// <article className="prose prose-invert prose-blue max-w-4xl mx-auto p-6 md:p-12 min-h-screen">
// <header className="mb-8 border-b border-zinc-800 pb-6">
// <h1 className="text-4xl font-extrabold text-white mb-2 m-0">{article.title}</h1>
// {article.updatedAt && (
// <p className="text-zinc-500 text-sm m-0">Zuletzt aktualisiert: {article.updatedAt}</p>
// )}
// </header>
// <MDXRemote
// source={article.rawContent}
// components={mdxComponents}
// options={mdxOptions as any}
// />
// </article>
<Article title={article.title} updatedAt={article.updatedAt}>
<MDXRemote
source={article.rawContent}
components={mdxComponents}
options={mdxOptions as any}
/>
</Article>
);
}
+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>
);
}
+17
View File
@@ -0,0 +1,17 @@
import Article from "@/components/wiki/Article";
import { getAllWikiPages } from "@/lib/wiki";
export default async function WikiIndexPage() {
const allPages = await getAllWikiPages();
return (
<Article title="Wiki">
<div className="flex flex-col gap-2">
{allPages.map(({ title, path }) => (
<a key={path} href={`/wiki/${path}`} className="hover:underline">
{title}
</a>
))}
</div>
</Article>
);
}
+45
View File
@@ -0,0 +1,45 @@
'use client';
import { useState } from 'react';
export function CopyButton({ code }: { code?: string }) {
const [copied, setCopied] = useState(false);
const handleCopy = async (e: React.MouseEvent<HTMLButtonElement>) => {
e.preventDefault();
// Falls kein expliziter Code übergeben wird, suchen wir den Text im Elternelement (Codeblock)
let textToCopy = code;
if (!textToCopy) {
const parent = e.currentTarget.closest('figure');
const codeElement = parent?.querySelector('code');
textToCopy = codeElement?.textContent || '';
}
if (textToCopy) {
await navigator.clipboard.writeText(textToCopy);
setCopied(true);
setTimeout(() => setCopied(false), 2000);
}
};
return (
<button
onClick={handleCopy}
className="absolute top-2.5 right-3 p-1.5 rounded-md bg-zinc-900 border border-zinc-800 text-zinc-400 hover:text-white hover:bg-zinc-800 transition-colors z-20"
aria-label="Code kopieren"
>
{copied ? (
// Check Icon (Erfolg)
<svg className="w-4 h-4 text-emerald-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
</svg>
) : (
// Clipboard Icon
<svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z" />
</svg>
)}
</button>
);
}
+63 -61
View File
@@ -1,7 +1,7 @@
import { useState, useEffect, ComponentPropsWithoutRef } from "react"; import { useState, useEffect, ComponentPropsWithoutRef } from "react";
import Card from "./Card" import Card from "./Card";
import { Input } from "./FormElements" import { Input } from "./FormElements";
interface SongsProps extends Omit<ComponentPropsWithoutRef<typeof Card>, "title" | "children"> { interface SongsProps extends Omit<ComponentPropsWithoutRef<typeof Card>, "title" | "children"> {
onSelectSong?: (song: Song) => void; onSelectSong?: (song: Song) => void;
@@ -9,7 +9,7 @@ interface SongsProps extends Omit<ComponentPropsWithoutRef<typeof Card>, "title"
} }
interface Song { interface Song {
song_id: number; id: number;
songbook_id: number; songbook_id: number;
song_number: string; song_number: string;
title: string; title: string;
@@ -17,43 +17,42 @@ interface Song {
interface Songbook { interface Songbook {
id: number; id: number;
name: string; title: string;
language: 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 [song_search_name, setSongSearchName] = useState("");
const [searchResults, setSearchResults] = useState<Song[]>([]); const [searchResults, setSearchResults] = useState<Song[]>([]);
const [allSongs, setAllSongs] = useState<Song[]>([]); const [allSongs, setAllSongs] = useState<Song[]>([]);
const [songbooks, setSongbooks] = useState<Songbook[]>([]); const [songbooks, setSongbooks] = useState<Songbook[]>([]);
const search = (query: string) => { const search = (query: string) => {
setSongSearchName(query); setSongSearchName(query);
if (query.trim() !== "") { if (query.trim() !== "") {
setSearchResults( setSearchResults(
allSongs.filter((song) => allSongs.filter((song) =>
song.title.toLowerCase().includes(query.toLowerCase()) || song.title.toLowerCase().includes(query.toLowerCase()) ||
song.song_number.includes(query) song.song_number.includes(query)
) )
); );
} else { } else {
setSearchResults(allSongs); setSearchResults(allSongs);
} }
}; };
useEffect(() => { useEffect(() => {
const getSongslist = async () => { const getSongslist = async () => {
try { try {
const res = await fetch("/api/songs"); const res = await fetch("/api/songs");
if (res.ok) { if (res.ok) {
const data = await res.json(); const data = await res.json();
setAllSongs(data); setAllSongs(data);
setSearchResults(data); setSearchResults(data);
} }
} catch (error) { } catch (error) {
setAllSongs([]); setAllSongs([]);
console.error("Failed fetching songslist!"); console.error("Failed fetching songslist!", error);
} }
}; };
@@ -61,13 +60,14 @@ function Songs({ actionName, onSelectSong, className = "", ...props }: SongsProp
try { try {
const res = await fetch("/api/songbooks"); const res = await fetch("/api/songbooks");
if (res.ok) { if (res.ok) {
const data = await res.json(); const data = await res.json();
setSongbooks(data); setSongbooks(data);
} }
} catch (error) { } catch (error) {
console.error("Loading songbooks failed: ", error); console.error("Loading songbooks failed: ", error);
} }
} }
loadSongbooks(); loadSongbooks();
getSongslist(); getSongslist();
}, []); }, []);
@@ -80,64 +80,66 @@ function Songs({ actionName, onSelectSong, className = "", ...props }: SongsProp
> >
<div className="mb-4"> <div className="mb-4">
<Input.Text <Input.Text
type="text" type="text"
placeholder="Nach Songtitel oder Nummer suchen..." placeholder="Nach Songtitel oder Nummer suchen..."
value={song_search_name} value={song_search_name}
onChange={(e) => search(e.target.value)} onChange={(e) => search(e.target.value)}
/> />
</div> </div>
{/* TABELLE */} {/* 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"> <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"> <table className="w-full text-left border-collapse text-sm">
<thead className="bg-neutral-100 dark:bg-neutral-900 sticky top-0 border-b border-neutral-200 dark:border-neutral-800 z-10"> <thead className="bg-neutral-100 dark:bg-neutral-900 sticky top-0 border-b border-neutral-200 dark:border-neutral-800 z-10">
<tr> <tr>
<th className="p-3 text-xs font-semibold text-neutral-600 dark:text-neutral-400 uppercase tracking-wider">Titel</th> <th className="p-3 text-xs font-semibold text-neutral-600 dark:text-neutral-400 uppercase tracking-wider">Titel</th>
<th className="p-3 text-xs font-semibold text-neutral-600 dark:text-neutral-400 uppercase tracking-wider">Liederbuch</th> <th className="p-3 text-xs font-semibold text-neutral-600 dark:text-neutral-400 uppercase tracking-wider">Liederbuch</th>
<th className="p-3 text-xs font-semibold text-neutral-600 dark:text-neutral-400 uppercase tracking-wider text-center">Nummer</th> <th className="p-3 text-xs font-semibold text-neutral-600 dark:text-neutral-400 uppercase tracking-wider text-center">Nummer</th>
<th className="p-3 text-xs font-semibold text-neutral-600 dark:text-neutral-400 uppercase tracking-wider text-right">Aktion</th> <th className="p-3 text-xs font-semibold text-neutral-600 dark:text-neutral-400 uppercase tracking-wider text-right">Aktion</th>
</tr> </tr>
</thead> </thead>
<tbody className="divide-y divide-neutral-200 dark:divide-neutral-800"> <tbody className="divide-y divide-neutral-200 dark:divide-neutral-800">
{searchResults.length === 0 ? ( {searchResults.length === 0 ? (
<tr> <tr>
<td colSpan={4} className="p-8 text-center text-neutral-400 dark:text-neutral-500">Keine Lieder gefunden</td> <td colSpan={4} className="p-8 text-center text-neutral-400 dark:text-neutral-500">Keine Lieder gefunden</td>
</tr> </tr>
) : ( ) : (
searchResults.map((song) => { searchResults.map((song) => {
const songBook = songbooks.find((book) => book.id === song.songbook_id); 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"> return (
<td className="p-3 font-medium text-neutral-900 dark:text-white max-w-[180px] sm:max-w-none truncate"> <tr key={`${song.songbook_id}-${song.id}`} className="hover:bg-neutral-100/60 dark:hover:bg-neutral-900/40 transition">
{song.title} <td className="p-3 font-medium text-neutral-900 dark:text-white max-w-[180px] sm:max-w-none truncate">
<span className="block text-xs text-neutral-500 dark:text-neutral-400 sm:hidden mt-0.5"> {song.title}
{songBook ? songBook.name : "Unbekannt"} <span className="block text-xs text-neutral-500 dark:text-neutral-400 sm:hidden mt-0.5">
</span> {songBook ? songBook.title : "Unbekannt"}
</td> </span>
<td className="p-3 text-neutral-700 dark:text-neutral-300 hidden sm:table-cell"> </td>
{songBook ? songBook.name : "Unbekannt"} <td className="p-3 text-neutral-700 dark:text-neutral-300 hidden sm:table-cell">
</td> {songBook ? songBook.title : "Unbekannt"}
<td className="p-3 text-center font-mono text-blue-600 dark:text-blue-400 font-bold"> </td>
{song.song_number} <td className="p-3 text-center font-mono text-blue-600 dark:text-blue-400 font-bold">
</td> {song.song_number}
<td className="p-3 text-right"> </td>
<Input.Button <td className="p-3 text-right">
onClick={() => onSelectSong?.(song)} <Input.Button
className="bg-white dark:bg-black hover:bg-blue-600 dark:hover:bg-blue-600 border border-neutral-300 dark:border-neutral-700 hover:border-blue-600 dark:hover:border-blue-500 hover:text-white font-medium rounded-md px-3 py-1.5 transition text-xs" onClick={() => onSelectSong?.(song)}
> className="bg-white dark:bg-black hover:bg-blue-600 dark:hover:bg-blue-600 border border-neutral-300 dark:border-neutral-700 hover:border-blue-600 dark:hover:border-blue-500 hover:text-white font-medium rounded-md px-3 py-1.5 transition text-xs"
{actionName} >
</Input.Button> {actionName}
</td> </Input.Button>
</tr> </td>
); </tr>
);
}) })
)} )}
</tbody> </tbody>
</table> </table>
</div> </div>
</Card> </Card>
) );
} }
export const Screens = { export const Screens = {
Songs: Songs, Songs: Songs,
} };
+166
View File
@@ -0,0 +1,166 @@
import React from 'react';
import { CopyButton } from './CopyButton';
// 1. Callouts (Info, Warning, Error, Success)
export function Callout({
children,
type = 'info'
}: {
children: React.ReactNode;
type?: 'info' | 'warning' | 'error' | 'success'
}) {
// Farben für Hintergrund, Text und den linken Akzentstreifen (after)
const variants = {
info: "bg-blue-500/10 text-blue-200 after:bg-blue-500",
warning: "bg-amber-500/10 text-amber-200 after:bg-amber-500",
error: "bg-red-500/10 text-red-200 after:bg-red-500",
success: "bg-emerald-500/10 text-emerald-200 after:bg-emerald-500",
};
return (
<div
className={`relative overflow-hidden p-4 my-6 rounded-md
after:content-[''] after:absolute after:top-1 after:left-1 after:bottom-1 after:w-1 after:rounded
${variants[type]}`}
>
<div className="flex gap-3 items-center">
<div className="shrink-0">
{type === 'info' && <svg className="w-6 h-6 text-blue-400" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" /></svg>}
{type === 'warning' && <svg className="w-6 h-6 text-amber-400" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" /></svg>}
{type === 'error' && <svg className="w-6 h-6 text-red-400" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" /></svg>}
{type === 'success' && <svg className="w-6 h-6 text-emerald-400" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" /></svg>}
</div>
<div className="text-sm leading-relaxed [&>p]:m-0">{children}</div>
</div>
</div>
);
}
// 2. Grid & Cards
export function Grid({ children }: { children: React.ReactNode }) {
return <div className="grid grid-cols-1 md:grid-cols-2 gap-4 my-8">{children}</div>;
}
export function Card({ title, href, children }: { title: string; href: string; children: React.ReactNode }) {
return (
<a href={href} className="block p-6 bg-zinc-900 border border-zinc-800 rounded-xl hover:border-blue-500 transition-colors group no-underline">
<h3 className="text-lg font-bold text-white group-hover:text-blue-400 m-0 mb-2">{title}</h3>
<div className="text-zinc-400 text-sm m-0 leading-relaxed [&>p]:m-0">
{children}
</div>
</a>
);
}
// 3. Steps
export function Steps({ children }: { children: React.ReactNode }) {
// Wir gehen durch alle Kinder und fügen automatisch die 'stepNumber' als Prop hinzu
const steps = React.Children.map(children, (child, index) => {
if (React.isValidElement(child)) {
return React.cloneElement(child as React.ReactElement<any>, {
stepNumber: index + 1,
});
}
return child;
});
return (
<div className="ml-4 border-l border-zinc-800 pl-8 my-8 space-y-8">
{steps}
</div>
);
}
export function Step({
title,
children,
stepNumber
}: {
title: string;
children: React.ReactNode;
stepNumber?: number;
}) {
return (
<div className="relative">
{/* Die Nummer wird direkt als Text aus React gerendert */}
<div className="absolute -left-[41px] flex h-5 w-5 items-center justify-center rounded-full bg-zinc-900 border border-zinc-800 text-[10px] font-bold text-white">
{stepNumber}
</div>
<h3 className="text-white font-bold mb-2 mt-0 text-base">{title}</h3>
<div className="text-zinc-400 text-sm [&>p]:m-0">{children}</div>
</div>
);
}
// Custom Inline Code (verhindert das Erben auf große Codeblöcke)
export function InlineCode({ children, className, ...props }: React.HTMLAttributes<HTMLElement>) {
// Wenn 'data-theme' oder 'data-language' existiert, kommt das Element aus rehype-pretty-code (Code-Block)
const isCodeBlock = props && ('data-theme' in props || 'data-language' in props);
// Falls es Teil eines großen Codeblocks ist -> normales <code> ohne Inline-Styling rendern
if (isCodeBlock || className?.includes('language-')) {
return <code className={className} {...props}>{children}</code>;
}
// Ansonsten: Unser schickes Inline-Code-Design anwenden
return (
<code
className="px-1.5 py-0.5 rounded-md bg-zinc-800 text-pink-400 font-mono text-sm border border-zinc-700/50 before:content-none after:content-none"
{...props}
>
{children}
</code>
);
}
export function CodeBlockContainer({ children, ...props }: React.HTMLAttributes<HTMLPreElement>) {
return (
<div className="relative group">
<CopyButton />
<pre {...props}>{children}</pre>
</div>
);
}
export function API({
method = 'GET',
route,
children
}: {
method?: string;
route: string;
children?: React.ReactNode;
}) {
const methodUpper = method.toUpperCase();
// Farben für die verschiedenen HTTP-Methoden
const methodStyles: Record<string, string> = {
GET: 'bg-emerald-500/10 text-emerald-400 border-emerald-500/30',
POST: 'bg-blue-500/10 text-blue-400 border-blue-500/30',
PUT: 'bg-amber-500/10 text-amber-400 border-amber-500/30',
PATCH: 'bg-orange-500/10 text-orange-400 border-orange-500/30',
DELETE: 'bg-rose-500/10 text-rose-400 border-rose-500/30',
};
const badgeStyle = methodStyles[methodUpper] || 'bg-zinc-800 text-zinc-300 border-zinc-700';
return (
<div className="my-6 rounded-xl border border-zinc-800 bg-zinc-900/50 overflow-hidden">
{/* Route & Methoden-Header */}
<div className="flex items-center gap-3 p-4 bg-zinc-900 border-b border-zinc-800 font-mono text-sm">
<span className={`px-2.5 py-1 rounded-md text-xs font-bold border ${badgeStyle}`}>
{methodUpper}
</span>
<span className="text-zinc-200 font-semibold">/api/{route}</span>
</div>
{/* Beschreibung / Inhalt */}
{children && (
<div className="p-4 text-sm text-zinc-400 leading-relaxed [&>p]:m-0">
{children}
</div>
)}
</div>
);
}
+22
View File
@@ -0,0 +1,22 @@
import { ReactNode } from "react";
interface ArticleProps {
title: string;
updatedAt?: string;
children: ReactNode
}
export default function Article({ title, updatedAt, children }: ArticleProps) {
return (
<article className="prose prose-invert prose-blue max-w-4xl mx-auto p-6 md:p-12 min-h-screen">
<header className="mb-8 border-b border-zinc-800 pb-6">
<h1 className="text-4xl font-extrabold text-white mb-2 m-0">{title}</h1>
{updatedAt && (
<p className="text-zinc-500 text-sm m-0">Zuletzt aktualisiert: {updatedAt}</p>
)}
</header>
{children}
</article>
);
}
+34
View File
@@ -0,0 +1,34 @@
---
title: Lied erstellen
updatedAt: "2026-08-05"
---
<Steps>
<Step title="Verwaltungsseite aufrufen">
Navigiere im Browser auf `http://<ip>:3000/admin` (oder falls lokal gehostet: `http://localhost:3000/admin`).
</Step>
<Step title="Liederbuch auswählen">
Wähle in der Karte "Lied hinzufügen" oder "CSV-Massenimport" ein Liederbuch aus.
</Step>
<Step title="Lied hinzufügen">
Gib in der Karte "Lied hinzufügen" die Nummer und den Namen des Liedes ein. Bestätige mit "Lied speichern".
<img src="https://git.schamagusa.de/Schanbro/PsalmTafel/raw/branch/main/wiki/new_song.png" alt="Neues Lied hinzufügen" />
Alternativ in der Karte "CSV-Massenimport" eine CSV-Datei hochladen und mit "Hochladen & Verarbeiten" bestäigen.
<img src="https://git.schamagusa.de/Schanbro/PsalmTafel/raw/branch/main/wiki/csv_import.png" alt="CSV-Massenimport" />
<Callout type="important">
Das Format der CSV-Datei muss wie folgt aufgebaut sein:
```csv
nummer;title
[Lied-Nummer];[Lied-Titel]
```
**Beispiel:**
```csv
nummer;title
24;Die Schwalbe lieb und klein
596;Von guten Mächten wunderbar geborgen
```
</Callout>
</Step>
</Steps>
+14
View File
@@ -0,0 +1,14 @@
---
title: Liederbuch erstellen
updatedAt: "2026-08-05"
---
<Steps>
<Step title="Verwaltungsseite aufrufen">
Navigiere im Browser auf `http://<ip>:3000/admin` (oder falls lokal gehostet: `http://localhost:3000/admin`).
</Step>
<Step title="Liederbuch hinzufügen">
Gib in der Karte "Neues Liederbuch" die Namen und optional die Sprache des Liederbuchs ein. Bestätige mit "Liederbuch erstellen".
<img src="https://git.schamagusa.de/Schanbro/PsalmTafel/raw/branch/main/wiki/new_songbook.png" alt="Neues Liederbuch hinzufügen" />
</Step>
</Steps>
+49
View File
@@ -0,0 +1,49 @@
---
title: Installation & Setup
updatedAt: "2026-08-05"
----
<Callout type="warning">
Dieses Projekt befindet sich noch in der **aktiven Entwicklungsphase**. Bitte verwende es noch nicht für den produktiven Einsatz.
</Callout>
## Installation
<Steps>
<Step title="Repository klonen">
Nutze Git, um den Code zu holen:
```bash
git clone https://git.schamagusa.de/Schanbro/PsalmTafel.git
```
</Step>
<Step title="Navigiere in den erzeugten Ordner">
Nutze cd, um in den Ordner zu navigieren:
```bash
cd PsalmTafel
```
</Step>
<Step title="Abhängigkeiten installieren">
Führe den Installer aus:
```bash
npm install
```
</Step>
</Steps>
## Setup
<Steps>
<Step title="Datenbank einrichten lassen">
Führe die Einrichtung der Datenbank aus:
```bash
prisma generate
npx prisma migrate dev
```
</Step>
<Step title="Server starten">
Führe den Installer aus:
```bash
pnpm dev
```
</Step>
</Steps>
+50
View File
@@ -0,0 +1,50 @@
---
title: Test Page
updatedAt: "2026-08-04"
---
Willkommen im offiziellen Wiki! Hier findest du alle Informationen zum Projekt.
<Grid>
<Card title="Installation" href="/wiki/installation">
Erfahre, wie du das Projekt lokal aufsetzt.
</Card>
<Card title="Deployment" href="/wiki/deployment">
So bringst du deinen Code live auf den Server.
</Card>
</Grid>
## Schnellstart
<Steps>
<Step title="Repository klonen">
Nutze Git, um den Code zu holen:
`git clone ...`
</Step>
<Step title="Abhängigkeiten installieren">
Führe den Installer aus:
`pnpm install`
</Step>
</Steps>
<Callout type="warning">
Vergiss nicht, die `.env` Datei anzulegen, sonst startet die App nicht!
</Callout>
<Callout type="success">
Du bist jetzt bereit zum Entwickeln!
</Callout>
<Callout type="info">
Du bist jetzt bereit zum Entwickeln!
</Callout>
<Callout type="error">
Du bist jetzt bereit zum Entwickeln!
</Callout>
```typescript
function sayHello(name: string): string {
return `Hallo, ${name}!`;
}
```
+184 -13
View File
@@ -1,18 +1,189 @@
import { prisma } from "@/lib/db/prisma" import { prisma } from "@/lib/db/prisma"
import argon2 from 'argon2'
// If you want to implement user, just uncomment this.
// import argon2 from 'argon2'
// TEST
// import { getSongs, getSongById, searchSongsByTitle, createSong, updateSong, deleteSong } from "@/lib/db/song";
// import { getSongBooks, getSongBookById, searchSongBooksByTitle, createSongBook, updateSongBook, deleteSongBook } from "@/lib/db/songbook";
// import { addSongToBook, updateSongInBook, removeSongFromBook, getSongByNumber, isSongNumberTaken } from "@/lib/db/songbooksongs";
// import { getUsers, getUserById, getUserByUsername, createUser, updateUser, deleteUser } from "@/lib/db/user";
// TEST
export async function initDB() { export async function initDB() {
const count = await prisma.user.count()
if (count === 0) { // TEST if Database works
await prisma.user.create({ const count = await prisma.user.count()
data: { console.log("Database OK");
username: process.env.ADMIN_USERNAME!,
password: await argon2.hash(process.env.ADMIN_PASSWORD!), // TEST
role: 'admin', // runTests();
name: 'Admin'
} // No need for users, in future maybe?
}) //
console.log('Created admin user') //
} // if (count === 0) {
// await prisma.user.create({
// data: {
// username: process.env.ADMIN_USERNAME!,
// password: await argon2.hash(process.env.ADMIN_PASSWORD!),
// role: 'admin',
// name: 'Admin'
// }
// })
// console.log('Created admin user')
// }
} }
async function runTests() {
// ==========================================
// TEST: USER
// ==========================================
console.log("\n############ USER #############");
const user1 = await createUser({ username: "1 User", password: "admin" });
if (user1.success) {
console.log("✅ [PASSED] create user 1");
} else {
console.log("❌ [FAILED] create user 1", user1);
}
const user1_dupl = await createUser({ username: "1 User", password: "admin" });
if (!user1_dupl.success) {
console.log("✅ [PASSED] prevent duplicate user");
} else {
console.log("❌ [FAILED] prevent duplicate user", user1_dupl);
}
const user2 = await createUser({ username: "UserUser", password: "Admin" });
if (user2.success) {
console.log("✅ [PASSED] create user 2");
} else {
console.log("❌ [FAILED] create user 2", user2);
}
const users = await getUsers();
const userList = users.users || users.data || [];
if (users.success && userList.length === 2) {
console.log("✅ [PASSED] getUsers count === 2");
} else {
console.log("❌ [FAILED] getUsers count (expected 2)", users);
}
// Weitere User Actions testen
const userById = await getUserById(1);
console.log(userById.success ? "✅ [PASSED] getUserById" : "❌ [FAILED] getUserById", userById);
const userByName = await getUserByUsername("1 User");
console.log(userByName.success ? "✅ [PASSED] getUserByUsername" : "❌ [FAILED] getUserByUsername", userByName);
const updatedUser = await updateUser(1, { username: "UserUserUser", role: "admin" });
console.log(updatedUser.success ? "✅ [PASSED] updateUser" : "❌ [FAILED] updateUser", updatedUser);
const deletedUser = await deleteUser(1);
console.log(deletedUser.success ? "✅ [PASSED] deleteUser" : "❌ [FAILED] deleteUser", deletedUser);
const deletedUser2 = await deleteUser(2);
console.log(deletedUser2.success ? "✅ [PASSED] deleteUser" : "❌ [FAILED] deleteUser", deletedUser2);
// ==========================================
// TEST: SONGBOOKS
// ==========================================
console.log("\n############ SONGBOOKS #############");
const sb1 = await createSongBook({ title: "Gesangbuch1", language: "DE" });
console.log(sb1.success ? "✅ [PASSED] createSongBook 1" : "❌ [FAILED] createSongBook 1", sb1);
const sb1_dupl = await createSongBook({ title: "Gesangbuch1", language: "DE" });
console.log(!sb1_dupl.success ? "✅ [PASSED] prevent duplicate songbook" : "❌ [FAILED] prevent duplicate songbook", sb1_dupl);
const sb2 = await createSongBook({ title: "Gesangbuch2", language: "DE" });
console.log(sb2.success ? "✅ [PASSED] createSongBook 2" : "❌ [FAILED] createSongBook 2", sb2);
const sbooks = await getSongBooks();
const sbookList = sbooks.songBooks || sbooks.data || [];
console.log(sbooks.success && sbookList.length === 2 ? "✅ [PASSED] getSongBooks count === 2" : "❌ [FAILED] getSongBooks count", sbooks);
const sbById = await getSongBookById(1);
console.log(sbById.success ? "✅ [PASSED] getSongBookById" : "❌ [FAILED] getSongBookById", sbById);
const sbSearch = await searchSongBooksByTitle("GesangBuch");
console.log(sbSearch.success && sbSearch.songBooks?.length === 2 ? "✅ [PASSED] searchSongBooksByTitle" : "❌ [FAILED] searchSongBooksByTitle", sbSearch);
const sbUpdate = await updateSongBook(1, { title: "Liederbuch", language: "Deutsch" });
console.log(sbUpdate.success ? "✅ [PASSED] updateSongBook" : "❌ [FAILED] updateSongBook", sbUpdate);
const sbDel = await deleteSongBook(2);
console.log(sbDel.success ? "✅ [PASSED] deleteSongBook" : "❌ [FAILED] deleteSongBook", sbDel);
// ==========================================
// TEST: SONGS
// ==========================================
console.log("\n############ SONGS #############");
const song1 = await createSong({ title: "1 Lied" });
console.log(song1.success ? "✅ [PASSED] createSong 1" : "❌ [FAILED] createSong 1", song1);
const song1_dupl = await createSong({ title: "1 Lied" });
console.log(!song1_dupl.success ? "✅ [PASSED] prevent duplicate song" : "❌ [FAILED] prevent duplicate song", song1_dupl);
const song2 = await createSong({ title: "Liiiied" });
console.log(song2.success ? "✅ [PASSED] createSong 2" : "❌ [FAILED] createSong 2", song2);
const songs = await getSongs();
const songList = songs.songs || songs.data || [];
console.log(songs.success && songList.length === 2 ? "✅ [PASSED] getSongs count === 2" : "❌ [FAILED] getSongs count", songs);
const songById = await getSongById(2);
console.log(songById.success ? "✅ [PASSED] getSongById" : "❌ [FAILED] getSongById", songById);
const songSearch = await searchSongsByTitle("liEd");
console.log(songSearch.success && songSearch.songs?.length === 1 ? "✅ [PASSED] searchSongsByTitle" : "❌ [FAILED] searchSongsByTitle", songSearch);
const songUpdate = await updateSong(1, { title: "Lied der Lieder" });
console.log(songUpdate.success ? "✅ [PASSED] updateSong" : "❌ [FAILED] updateSong", songUpdate);
await createSong({ title: "3 Lied" });
const songDel = await deleteSong(3);
console.log(songDel.success ? "✅ [PASSED] deleteSong" : "❌ [FAILED] deleteSong", songDel);
// ==========================================
// TEST: SONGBOOK SONGS (RELATIONS)
// ==========================================
console.log("\n############ SONGBOOKSONGS #############");
const addSong1 = await addSongToBook(1, 1, 1); // bookId, songId, songNumber
console.log(addSong1.success ? "✅ [PASSED] addSongToBook 1" : "❌ [FAILED] addSongToBook 1", addSong1);
const addSong1_dupl = await addSongToBook(1, 1, 1);
console.log(!addSong1_dupl.success ? "✅ [PASSED] prevent duplicate song in book" : "❌ [FAILED] prevent duplicate song in book", addSong1_dupl);
const addSong1_dupl2 = await addSongToBook(2, 1, 1);
console.log(!addSong1_dupl2.success ? "✅ [PASSED] prevent duplicate songnumber in book" : "❌ [FAILED] prevent duplicate songnumber in book", addSong1_dupl2);
const addSong2 = await addSongToBook(2, 1, 2);
console.log(addSong2.success ? "✅ [PASSED] addSongToBook 2" : "❌ [FAILED] addSongToBook 2", addSong2);
const songByNum = await getSongByNumber(1, 2);
console.log(songByNum.success ? "✅ [PASSED] getSongByNumber" : "❌ [FAILED] getSongByNumber", songByNum);
const updateInBook = await updateSongInBook(1, 1, { songNumber: 3 });
console.log(updateInBook.success ? "✅ [PASSED] updateSongInBook" : "❌ [FAILED] updateSongInBook", updateInBook);
const isTaken = await isSongNumberTaken(1, 2);
console.log(typeof isTaken === "boolean" || isTaken.success ? "✅ [PASSED] isSongNumberTaken" : "❌ [FAILED] isSongNumberTaken", isTaken);
const removeSong = await removeSongFromBook(1, 1);
console.log(removeSong.success ? "✅ [PASSED] removeSongFromBook" : "❌ [FAILED] removeSongFromBook", removeSong);
}
+46 -30
View File
@@ -1,4 +1,5 @@
import { prisma } from "@/lib/db/prisma"; import { prisma } from "@/lib/db/prisma";
import { parseInt } from "@/lib/helper/checkvar";
// For Error checking use this import: import { Prisma } from "@prisma/client"; // For Error checking use this import: import { Prisma } from "@prisma/client";
@@ -6,7 +7,7 @@ import { prisma } from "@/lib/db/prisma";
* GetSongs * GetSongs
* Returns all songs * Returns all songs
* *
* @returns {"success": boolean, "songs": [{"id":number, "title": string},...]} * @returns {"success": boolean, "status": number, "songs": [{"id":number, "title": string},...]}
*/ */
export async function getSongs() { export async function getSongs() {
try{ try{
@@ -20,10 +21,10 @@ export async function getSongs() {
], ],
}); });
return { success: true, songs }; return { success: true, status: 200, songs };
} catch(error) { } catch(error) {
console.error("Error in getSongs", error); console.error("Error in getSongs", error);
return { success: false, error: "Error while loading Songs" }; return { success: false, status: 500, error: "Error while loading Songs" };
} }
} }
@@ -32,10 +33,14 @@ export async function getSongs() {
* GetSongById * GetSongById
* Returns a song by his ID * Returns a song by his ID
* @param id - ID indicatin the song * @param id - ID indicatin the song
* @returns {"success": boolean, "song": {"id":number, "title": string, "songBooks": [{"songNumber": number, "book": {"title": string, "language": string}},...]}} * @returns {"success": boolean, "status": number, "song": {"id":number, "title": string, "songBooks": [{"songNumber": number, "book": {"title": string, "language": string}},...]}}
*/ */
export async function getSongById(id: number) { export async function getSongById(rawId: number) {
try{ try{
const id = parseInt(rawId);
if (!id) {
return { success: false, status: 400, error: "Id has to be Integer" };
}
const song = await prisma.song.findUnique({ const song = await prisma.song.findUnique({
where: { id }, where: { id },
select: { select: {
@@ -46,6 +51,7 @@ export async function getSongById(id: number) {
songNumber: true, songNumber: true,
book: { book: {
select: { select: {
id: true,
title: true, title: true,
language: true, language: true,
} }
@@ -56,13 +62,13 @@ export async function getSongById(id: number) {
}); });
if (!song) { if (!song) {
return { success: false, error: "Song not found" }; return { success: false, status: 404, error: "Song not found" };
} }
return { success: true, song }; return { success: true, status: 200, song };
} catch(error) { } catch(error) {
console.error("Error in getSongById", error); console.error("Error in getSongById", error);
return { success: false, error: "Error while loading Song" }; return { success: false, status: 500, error: "Error while loading Song" };
} }
} }
@@ -72,7 +78,7 @@ export async function getSongById(id: number) {
* *
* @param query - The search term for the song title. * @param query - The search term for the song title.
* @param limit - Max number of songs returned for performance (default: 20). * @param limit - Max number of songs returned for performance (default: 20).
* @returns Object with success state and an array of matching songs. * @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) { export async function searchSongsByTitle(query: string, limit: number = 20) {
try { try {
@@ -85,7 +91,6 @@ export async function searchSongsByTitle(query: string, limit: number = 20) {
where: { where: {
title: { title: {
contains: query.trim(), contains: query.trim(),
mode: "insensitive", // Textsearch
}, },
}, },
select: { select: {
@@ -106,10 +111,10 @@ export async function searchSongsByTitle(query: string, limit: number = 20) {
take: limit, take: limit,
}); });
return { success: true, songs }; return { success: true, status: 200, songs };
} catch (error) { } catch (error) {
console.error("Error in searchSongsByTitle:", error); console.error("Error in searchSongsByTitle:", error);
return { success: false, error: "Error while searching Songs" }; return { success: false, status: 500, error: "Error while searching Songs" };
} }
} }
@@ -117,13 +122,16 @@ export async function searchSongsByTitle(query: string, limit: number = 20) {
* CreateSong * CreateSong
* Creates an song and returns this song * Creates an song and returns this song
* @param data - object with title * @param data - object with title
* @returns {"success": boolean, "song": {"id":number, "title": string}} * @returns {"success": boolean, "status": number, "song": {"id":number, "title": string}}
*/ */
export async function createSong(data: { title: string }) { export async function createSong(data: { title: string }) {
try{ try{
if(!data.title){
return { success: false, status: 400, error: "Field 'title' is required" };
}
const song = await prisma.song.create({ const song = await prisma.song.create({
data: { data: {
title: data.title title: data.title.trim()
}, },
select: { select: {
id: true, id: true,
@@ -132,17 +140,17 @@ export async function createSong(data: { title: string }) {
}); });
if (!song) { if (!song) {
return { success: false, error: "Could not create song" }; return { success: false, status: 500, error: "Could not create song" };
} }
return { success: true, song }; return { success: true, status: 201, song };
} catch(error) { } catch(error) {
console.error("Error in createSong", error); console.error("Error in createSong", error);
// P2002 = Unique Constraint Violation (username) // P2002 = Unique Constraint Violation (username)
if (error.code === "P2002") { if (error.code === "P2002") {
return { success: false, error: "Song already exists" }; return { success: false, status: 409, error: "Song already exists" };
} }
return { success: false, error: "Error while creating Song" }; return { success: false, status: 500, error: "Error while creating Song" };
} }
} }
@@ -151,13 +159,17 @@ export async function createSong(data: { title: string }) {
* Updates an existing song and returns the updated song * Updates an existing song and returns the updated song
* @param id - ID indicatin the song * @param id - ID indicatin the song
* @param data - object with title * @param data - object with title
* @returns {"success": boolean, "song": {"id": number, "title": string}} * @returns {"success": boolean, "status": number, "song": {"id": number, "title": string}}
*/ */
export async function updateSong( export async function updateSong(
id: number, rawId: number,
data: { title?: string } data: { title?: string }
) { ) {
try { try {
const id = parseInt(rawId);
if (!id) {
return { success: false, status: 400, error: "Id has to be Integer" };
}
// Prepare update fields dynamically // Prepare update fields dynamically
const updateData: { title?: string } = {}; const updateData: { title?: string } = {};
@@ -167,7 +179,7 @@ export async function updateSong(
// If no fields to update were provided // If no fields to update were provided
if (Object.keys(updateData).length === 0) { if (Object.keys(updateData).length === 0) {
return { success: false, error: "No fields provided to update" }; return { success: false, status: 400, error: "No fields provided to update" };
} }
const song = await prisma.song.update({ const song = await prisma.song.update({
@@ -179,19 +191,19 @@ export async function updateSong(
} }
}); });
return { success: true, song }; return { success: true, status: 200, song };
} catch (error) { } catch (error) {
console.error("Error in updateSong", error); console.error("Error in updateSong", error);
// P2025 = Record to update not found // P2025 = Record to update not found
if (error.code === "P2025") { if (error.code === "P2025") {
return { success: false, error: "Song not found" }; return { success: false, status: 404, error: "Song not found" };
} }
// P2002 = Unique Constraint Violation (username) // P2002 = Unique Constraint Violation (username)
if (error.code === "P2002") { if (error.code === "P2002") {
return { success: false, error: "Song already exists" }; return { success: false, status: 409, error: "Song already exists" };
} }
return { success: false, error: "Error while updating Song" }; return { success: false, status: 500, error: "Error while updating Song" };
} }
} }
@@ -199,10 +211,14 @@ export async function updateSong(
* DeleteSong * DeleteSong
* Deletes an existing song and returns the deleted song * Deletes an existing song and returns the deleted song
* @param id - ID indicatin the song * @param id - ID indicatin the song
* @returns {"success": boolean, "song": {"id": number, "title": string}} * @returns {"success": boolean, "status": number, "song": {"id": number, "title": string}}
*/ */
export async function deleteSong(id: number) { export async function deleteSong(rawId: number) {
try { try {
const id = parseInt(rawId);
if (!id) {
return { success: false, status: 400, error: "Id has to be Integer" };
}
const song = await prisma.song.delete({ const song = await prisma.song.delete({
where: { id }, where: { id },
select: { select: {
@@ -211,14 +227,14 @@ export async function deleteSong(id: number) {
} }
}); });
return { success: true, song }; return { success: true, status: 200, song };
} catch (error) { } catch (error) {
console.error("Error in deleteSong", error); console.error("Error in deleteSong", error);
// P2025 = Record to update not found // P2025 = Record to update not found
if (error.code === "P2025") { if (error.code === "P2025") {
return { success: false, error: "Song not found" }; return { success: false, status: 404, error: "Song not found" };
} }
return { success: false, error: "Error while deleting Song" }; return { success: false, status: 500, error: "Error while deleting Song" };
} }
} }
+91 -24
View File
@@ -1,4 +1,5 @@
import { prisma } from "@/lib/db/prisma"; import { prisma } from "@/lib/db/prisma";
import { parseInt } from "@/lib/helper/checkvar";
/** /**
@@ -9,7 +10,7 @@ import { prisma } from "@/lib/db/prisma";
*/ */
export async function getSongBooks() { export async function getSongBooks() {
try { try {
const songBooks = await prisma.songBookModel.findMany({ // Name deines Prisma-Modells für Bücher const songBooks = await prisma.songBook.findMany({
select: { select: {
id: true, id: true,
title: true, title: true,
@@ -20,10 +21,10 @@ export async function getSongBooks() {
}, },
}); });
return { success: true, songBooks }; return { success: true, status: 200, songBooks };
} catch (error) { } catch (error) {
console.error("Error in getSongBooks:", error); console.error("Error in getSongBooks:", error);
return { success: false, error: "Error while loading SongBooks" }; return { success: false, status: 500, error: "Error while loading SongBooks" };
} }
} }
@@ -34,9 +35,13 @@ export async function getSongBooks() {
* @param id - ID indicating the songbook * @param id - ID indicating the songbook
* @returns {"success": boolean, "songBook": object} * @returns {"success": boolean, "songBook": object}
*/ */
export async function getSongBookById(id: number) { export async function getSongBookById(rawId: number) {
try { try {
const songBook = await prisma.songBookModel.findUnique({ const id = parseInt(rawId);
if (!id) {
return { success: false, status: 400, error: "Id has to be Integer" };
}
const songBook = await prisma.songBook.findUnique({
where: { id }, where: { id },
select: { select: {
id: true, id: true,
@@ -60,13 +65,13 @@ export async function getSongBookById(id: number) {
}); });
if (!songBook) { if (!songBook) {
return { success: false, error: "SongBook not found" }; return { success: false, status: 404, error: "SongBook not found" };
} }
return { success: true, songBook }; return { success: true, status: 200, songBook };
} catch (error) { } catch (error) {
console.error("Error in getSongBookById:", error); console.error("Error in getSongBookById:", error);
return { success: false, error: "Error while loading SongBook" }; return { success: false, status: 500, error: "Error while loading SongBook" };
} }
} }
@@ -82,14 +87,13 @@ export async function searchSongBooksByTitle(query: string, limit: number = 20)
try { try {
const cleanQuery = query.trim(); const cleanQuery = query.trim();
if (!cleanQuery) { if (!cleanQuery) {
return { success: true, songBooks: [] }; return { success: true, status: 200, songBooks: [] };
} }
const songBooks = await prisma.songBookModel.findMany({ const songBooks = await prisma.songBook.findMany({
where: { where: {
title: { title: {
contains: cleanQuery, contains: cleanQuery,
mode: "insensitive", // Textsearch
}, },
}, },
select: { select: {
@@ -114,10 +118,10 @@ export async function searchSongBooksByTitle(query: string, limit: number = 20)
take: limit, take: limit,
}); });
return { success: true, songBooks }; return { success: true, status: 200, songBooks };
} catch (error) { } catch (error) {
console.error("Error in searchSongBooksByTitle:", error); console.error("Error in searchSongBooksByTitle:", error);
return { success: false, error: "Error while searching SongBooks" }; return { success: false, status: 500, error: "Error while searching SongBooks" };
} }
} }
@@ -130,10 +134,13 @@ export async function searchSongBooksByTitle(query: string, limit: number = 20)
*/ */
export async function createSongBook(data: { title: string; language: string }) { export async function createSongBook(data: { title: string; language: string }) {
try { try {
const songBook = await prisma.songBookModel.create({ if(!data.title){
return { success: false, status: 400, error: "Field 'title' is required" };
}
const songBook = await prisma.songBook.create({
data: { data: {
title: data.title, title: data.title.trim(),
language: data.language, language: data.language?.trim() ?? "",
}, },
select: { select: {
id: true, id: true,
@@ -142,14 +149,70 @@ export async function createSongBook(data: { title: string; language: string })
}, },
}); });
return { success: true, songBook }; return { success: true, status: 201, songBook };
} catch (error) { } catch (error) {
if (error.code === "P2002") { if (error.code === "P2002") {
return { success: false, error: "SongBook title already exists" }; return { success: false, status: 409, error: "SongBook title already exists" };
} }
console.error("Error in createSongBook:", error); console.error("Error in createSongBook:", error);
return { success: false, error: "Error while creating SongBook" }; return { success: false, status: 500, error: "Error while creating SongBook" };
}
}
/**
* UpdateSongBook
* Updates an existing songbook by ID
*
* @param id - ID of the songbook to update
* @param data - object with optional title and language
* @returns {"success": boolean, "songBook": {"id": number, "title": string, "language": string}}
*/
export async function updateSongBook(
rawId: number,
data: { title?: string; language?: string }
) {
try {
const id = parseInt(rawId);
if (!id) {
return { success: false, status: 400, error: "Id has to be Integer" };
}
// Prepare update fields dynamically
const updateData: { title?: string; language?: string } = {};
if (data.title) {
updateData.title = data.title.trim();
}
if (data.language) {
updateData.language = data.language.trim();
}
// If no fields to update were provided
if (Object.keys(updateData).length === 0) {
return { success: false, status: 400, error: "No fields provided to update" };
}
const songBook = await prisma.songBook.update({
where: { id },
data: updateData,
select: {
id: true,
title: true,
language: true,
},
});
return { success: true, status: 200, songBook };
} catch (error: any) {
if (error.code === "P2025") {
return { success: false, status: 404, error: "SongBook not found" };
}
if (error.code === "P2002") {
return { success: false, status: 500, error: "SongBook title already exists" };
}
console.error("Error in updateSongBook:", error);
return { success: false, error: "Error while updating SongBook" };
} }
} }
@@ -160,9 +223,13 @@ export async function createSongBook(data: { title: string; language: string })
* @param id - ID indicating the songbook * @param id - ID indicating the songbook
* @returns {"success": boolean, "songBook": object} * @returns {"success": boolean, "songBook": object}
*/ */
export async function deleteSongBook(id: number) { export async function deleteSongBook(rawId: number) {
try { try {
const songBook = await prisma.songBookModel.delete({ const id = parseInt(rawId);
if (!id) {
return { success: false, status: 400, error: "Id has to be Integer" };
}
const songBook = await prisma.songBook.delete({
where: { id }, where: { id },
select: { select: {
id: true, id: true,
@@ -186,13 +253,13 @@ export async function deleteSongBook(id: number) {
}); });
if (!songBook) { if (!songBook) {
return { success: false, error: "SongBook not found" }; return { success: false, status: 404, error: "SongBook not found" };
} }
return { success: true, songBook }; return { success: true, status: 200, songBook };
} catch (error) { } catch (error) {
console.error("Error in deleteSongBook:", error); console.error("Error in deleteSongBook:", error);
return { success: false, error: "Error while deleting SongBook" }; return { success: false, status: 500, error: "Error while deleting SongBook" };
} }
} }
+92 -45
View File
@@ -1,5 +1,13 @@
import { prisma } from "@/lib/db/prisma"; import { prisma } from "@/lib/db/prisma";
import { parseInt } from "@/lib/helper/checkvar";
export type DbResponse =
| { success: true; status: number, entry: {
songId: number | undefined;
songBookId: number | undefined;
songNumber: string | undefined
}, song: {id: number, title: string} | undefined }
| { success: false; status: number; error: string };
/** /**
* AddSongToBook * AddSongToBook
@@ -8,33 +16,45 @@ import { prisma } from "@/lib/db/prisma";
* @param songId - ID of the song * @param songId - ID of the song
* @param bookId - ID of the songbook * @param bookId - ID of the songbook
* @param songNumber - Track/Song number in that specific book * @param songNumber - Track/Song number in that specific book
* @returns {"success": boolean, "entry": {"songId": number, "bookId": number, "songNumber": number}} * @returns {"success": boolean, "status": number, "entry": {"songId": number, "bookId": number, "songNumber": number}}
*/ */
export async function addSongToBook(songId: number, bookId: number, songNumber: number) { export async function addSongToBook(rawSongId: number, rawSongBookId: number, rawSongNumber: string): Promise<DbResponse> {
try { try {
const isTaken = await isSongNumberTaken(bookId, songNumber); const songId = parseInt(rawSongId);
if (!songId) {
return { success: false, status: 400, error: "SongId has to be Integer" };
}
const songBookId = parseInt(rawSongBookId);
if (!songBookId) {
return { success: false, status: 400, error: "SongbookId has to be Integer" };
}
const songNumber = rawSongNumber?.trim() ?? null;
if(!songNumber){
return { success: false, status: 400, error: "Field 'SongNumber' ist required" };
}
const isTaken = await isSongNumberTaken(songBookId, songNumber);
if (isTaken) { if (isTaken) {
return { success: false, error: "Songnumber already taken in this songbook" }; return { success: false, status: 409, error: "Songnumber already taken in this songbook" };
} }
const entry = await prisma.songBook.create({ // Verknüpfungs-Tabelle const entry = await prisma.songBookSongs.create({
data: { data: {
songId, songId,
bookId, songBookId,
songNumber, songNumber,
}, },
}); });
return { success: true, entry }; return { success: true, status: 200, entry };
} catch (error) { } catch (error) {
if (error.code === "P2002") { if (error.code === "P2002") {
return { success: false, error: "Song is already in this book" }; return { success: false, status: 409, error: "Song is already in this book" };
} }
console.error("Error in addSongToBook:", error); console.error("Error in addSongToBook:", error);
return { success: false, error: "Error while adding song to book" }; return { success: false, status: 500, error: "Error while adding song to book" };
} }
} }
@@ -45,48 +65,58 @@ export async function addSongToBook(songId: number, bookId: number, songNumber:
* @param songId - ID of the song * @param songId - ID of the song
* @param bookId - ID of the songbook * @param bookId - ID of the songbook
* @param data - Object of the new data * @param data - Object of the new data
* @returns {"success": true, "entry": {"songId": number, "bookId": number, "songNumber": number}} | {"success": false, "error": string} * @returns {"success": true, "status": number, "entry": {"songId": number, "bookId": number, "songNumber": number}} | {"success": false, "error": string}
*/ */
export async function updateSongInBook(songId: number, bookId: number, data: {songNumber: number}) { export async function updateSongInBook(rawSongId: number, rawSongBookId: number, data: {number: string}) {
try { try {
// 1. Prüfen, ob die neue Nummer bereits vergeben ist const songId = parseInt(rawSongId);
const isTaken = await isSongNumberTaken(bookId, data.songNumber); if (!songId) {
return { success: false, status: 400, error: "Id has to be Integer" };
}
const songBookId = parseInt(rawSongBookId);
if (!songBookId) {
return { success: false, status: 400, error: "Id has to be Integer" };
}
const songNumber = data.number?.trim() ?? null;
if(!songNumber){
return { success: false, status: 400, error: "Field 'SongNumber' ist required" };
}
const isTaken = await isSongNumberTaken(songBookId, songNumber);
if (isTaken) { if (isTaken) {
return { success: false, error: "New song number is already taken in this songbook" }; return { success: false, status: 409, error: "New song number is already taken in this songbook" };
} }
// 2. Eintrag über den Composite Primary Key (songId_bookId) aktualisieren const entry = await prisma.songBookSongs.update({
const entry = await prisma.songBook.update({
where: { where: {
songId_bookId: { songBookId_songId: {
songId, songId,
bookId, songBookId,
}, },
}, },
data: { data: {
songNumber: data.songNumber, songNumber,
}, },
select: { select: {
songId: true, songId: true,
bookId: true, songBookId: true,
songNumber: true, songNumber: true,
}, },
}); });
return { success: true, entry }; return { success: true, status: 200, entry };
} catch (error: any) { } catch (error: any) {
// P2025 = Record to update not found (Verknüpfung existiert noch gar nicht) // P2025 = Record to update not found
if (error?.code === "P2025") { if (error?.code === "P2025") {
return { success: false, error: "Song is not assigned to this songbook" }; return { success: false, status: 404, error: "Song is not assigned to this songbook" };
} }
// P2002 = Unique Constraint Violation (z.B. neue Nummer doch schon besetzt) // P2002 = Unique Constraint Violation
if (error?.code === "P2002") { if (error?.code === "P2002") {
return { success: false, error: "Song number already exists in this songbook" }; return { success: false, status: 409, error: "Song number already exists in this songbook" };
} }
console.error("Error in updateSongInBook:", error); console.error("Error in updateSongInBook:", error);
return { success: false, error: "Error while updating song in book" }; return { success: false, status: 500, error: "Error while updating song in book" };
} }
} }
@@ -96,26 +126,35 @@ export async function updateSongInBook(songId: number, bookId: number, data: {so
* *
* @param songId - ID of the song * @param songId - ID of the song
* @param bookId - ID of the songbook * @param bookId - ID of the songbook
* @returns {"success": boolean, "status": number}
*/ */
export async function removeSongFromBook(songId: number, bookId: number) { export async function removeSongFromBook(rawSongId: number, rawSongBookId: number) {
try { try {
await prisma.songBook.delete({ const songId = parseInt(rawSongId);
if (!songId) {
return { success: false, status: 400, error: "Id has to be Integer" };
}
const songBookId = parseInt(rawSongBookId);
if (!songBookId) {
return { success: false, status: 400, error: "Id has to be Integer" };
}
const entry = await prisma.songBookSongs.delete({
where: { where: {
songId_bookId: { songBookId_songId: {
songId, songId,
bookId, songBookId,
}, },
}, },
}); });
return { success: true }; return { success: true, status: 200, entry };
} catch (error) { } catch (error) {
if (error.code === "P2025") { if (error.code === "P2025") {
return { success: false, error: "Song assignment not found" }; return { success: false, status: 404, error: "Song assignment not found" };
} }
console.error("Error in removeSongFromBook:", error); console.error("Error in removeSongFromBook:", error);
return { success: false, error: "Error while removing song from book" }; return { success: false, status: 500, error: "Error while removing song from book" };
} }
} }
@@ -124,14 +163,22 @@ export async function removeSongFromBook(songId: number, bookId: number) {
* *
* @param bookId - The ID of the songbook * @param bookId - The ID of the songbook
* @param songNumber - The song number in that book * @param songNumber - The song number in that book
* @returns {"success": true, "entry": {"songNumber": number "song": {"id": number, "title": string}}} * @returns {"success": true, "status": number, "entry": {"songNumber": number "song": {"id": number, "title": string}}}
*/ */
export async function getSongByNumber(bookId: number, songNumber: number) { export async function getSongByNumber(rawSongBookId: number, rawSongNumber: string) {
try { try {
const songBookId = parseInt(rawSongBookId);
if (!songBookId) {
return { success: false, status: 400, error: "Id has to be Integer" };
}
const songNumber = rawSongNumber?.trim() ?? null;
if(!songNumber){
return { success: false, status: 400, error: "Field 'SongNumber' ist required" };
}
const entry = await prisma.songBookSongs.findFirst({ const entry = await prisma.songBookSongs.findFirst({
where: { where: {
songBookId: bookId, songBookId,
songNumber: songNumber, songNumber,
}, },
select: { select: {
songNumber: true, songNumber: true,
@@ -145,13 +192,13 @@ export async function getSongByNumber(bookId: number, songNumber: number) {
}); });
if (!entry) { if (!entry) {
return { success: false, error: "No song found for this number" }; return { success: false, status: 404, error: "No song found for this number" };
} }
return { success: true, entry }; return { success: true, status: 200, entry };
} catch (error) { } catch (error) {
console.error("Error in getSongByNumber:", error); console.error("Error in getSongByNumber:", error);
return { success: false, error: "Error while fetching song by number" }; return { success: false, status: 500, error: "Error while fetching song by number" };
} }
} }
@@ -162,19 +209,19 @@ export async function getSongByNumber(bookId: number, songNumber: number) {
* @param songNumber - The song number to check * @param songNumber - The song number to check
* @returns true if taken, false if available * @returns true if taken, false if available
*/ */
export async function isSongNumberTaken(bookId: number, songNumber: number): Promise<boolean> { export async function isSongNumberTaken(songBookId: number, songNumber: string): Promise<boolean> {
try { try {
const existing = await prisma.songBook.findFirst({ const existing = await prisma.songBookSongs.findFirst({
where: { where: {
bookId, songBookId: songBookId,
songNumber, songNumber: songNumber,
}, },
select: { select: {
songId: true, songId: true,
}, },
}); });
return existing !== null; return existing != null;
} catch (error) { } catch (error) {
console.error("Error in isSongNumberTaken:", error); console.error("Error in isSongNumberTaken:", error);
return true; // If Error->Number is taken return true; // If Error->Number is taken
+27 -27
View File
@@ -5,7 +5,7 @@ import argon2 from "argon2";
* GetUsers * GetUsers
* Returns all users * Returns all users
* *
* @returns {"success": boolean, "users": [{"id":number, "username": string, "role": string},...]} * @returns {"success": boolean, "status":number, "users": [{"id":number, "username": string, "role": string},...]}
*/ */
export async function getUsers() { export async function getUsers() {
try{ try{
@@ -20,10 +20,10 @@ export async function getUsers() {
], ],
}); });
return { success: true, users }; return { success: true, status: 200, users };
} catch(error) { } catch(error) {
console.error("Error in getUsers", error); console.error("Error in getUsers", error);
return { success: false, error: "Error while loading Users" }; return { success: false, status: 500, error: "Error while loading Users" };
} }
} }
@@ -31,7 +31,7 @@ export async function getUsers() {
* GetUserById * GetUserById
* Returns a user by his ID * Returns a user by his ID
* @param id - ID indicatin the user * @param id - ID indicatin the user
* @returns {"success": boolean, "user": {"id":number, "username": string, "role": string}} * @returns {"success": boolean, "status":number, "user": {"id":number, "username": string, "role": string}}
*/ */
export async function getUserById(id: number) { export async function getUserById(id: number) {
try{ try{
@@ -45,13 +45,13 @@ export async function getUserById(id: number) {
}); });
if (!user) { if (!user) {
return { success: false, error: "User not found" }; return { success: false, status: 404, error: "User not found" };
} }
return { success: true, user }; return { success: true, status: 200, user };
} catch(error) { } catch(error) {
console.error("Error in getUserById", error); console.error("Error in getUserById", error);
return { success: false, error: "Error while loading User" }; return { success: false, status: 500, error: "Error while loading User" };
} }
} }
@@ -59,7 +59,7 @@ export async function getUserById(id: number) {
* GetUserByUsername * GetUserByUsername
* Returns a user by his username * Returns a user by his username
* @param username - Username of the user * @param username - Username of the user
* @returns {"success": boolean, "user": {"id":number, "username": string, "role": string}} * @returns {"success": boolean, "status":number, "user": {"id":number, "username": string, "role": string}}
*/ */
export async function getUserByUsername(username: string) { export async function getUserByUsername(username: string) {
try{ try{
@@ -73,13 +73,13 @@ export async function getUserByUsername(username: string) {
}); });
if (!user) { if (!user) {
return { success: false, error: "User not found" }; return { success: false, status: 404, error: "User not found" };
} }
return { success: true, user }; return { success: true, status: 200, user };
} catch(error) { } catch(error) {
console.error("Error in getUserByUsername", error); console.error("Error in getUserByUsername", error);
return { success: false, error: "Error while loading User" }; return { success: false, status: 500, error: "Error while loading User" };
} }
} }
@@ -87,9 +87,9 @@ export async function getUserByUsername(username: string) {
* CreateUser * CreateUser
* Creates an user and returns this user * Creates an user and returns this user
* @param data - object with username, password and optional role * @param data - object with username, password and optional role
* @returns {"success": boolean, "user": {"id":number, "username": string, "role": string}} * @returns {"success": boolean, "status":number, "user": {"id":number, "username": string, "role": string}}
*/ */
export async function CreateUser(data: { username: string; password: string; role?: string }) { export async function createUser(data: { username: string; password: string; role?: string }) {
try{ try{
const hash = await argon2.hash(data.password); const hash = await argon2.hash(data.password);
const user = await prisma.user.create({ const user = await prisma.user.create({
@@ -106,17 +106,17 @@ export async function CreateUser(data: { username: string; password: string; rol
}); });
if (!user) { if (!user) {
return { success: false, error: "Could not create user" }; return { success: false, status: 500, error: "Could not create user" };
} }
return { success: true, user }; return { success: true, status: 201, user };
} catch(error) { } catch(error) {
console.error("Error in createUser", error); console.error("Error in createUser", error);
// P2002 = Unique Constraint Violation // P2002 = Unique Constraint Violation
if (error.code === "P2002") { if (error.code === "P2002") {
return { success: false, error: "Username aready exists",}; return { success: false, status: 409, error: "Username aready exists",};
} }
return { success: false, error: "Error while creating User" }; return { success: false, status: 500, error: "Error while creating User" };
} }
} }
@@ -125,7 +125,7 @@ export async function CreateUser(data: { username: string; password: string; rol
* Updates an existing user and returns the updated user * Updates an existing user and returns the updated user
* @param id - ID indicatin the user * @param id - ID indicatin the user
* @param data - object with optionally username, password and role * @param data - object with optionally username, password and role
* @returns {"success": boolean, "user": {"id": number, "username": string, "role": string}} * @returns {"success": boolean, "status":number, "user": {"id": number, "username": string, "role": string}}
*/ */
export async function updateUser( export async function updateUser(
id: number, id: number,
@@ -149,7 +149,7 @@ export async function updateUser(
// If no fields to update were provided // If no fields to update were provided
if (Object.keys(updateData).length === 0) { if (Object.keys(updateData).length === 0) {
return { success: false, error: "No fields provided to update" }; return { success: false, status: 400, error: "No fields provided to update" };
} }
const user = await prisma.user.update({ const user = await prisma.user.update({
@@ -162,19 +162,19 @@ export async function updateUser(
} }
}); });
return { success: true, user }; return { success: true, status: 200, user };
} catch (error) { } catch (error) {
console.error("Error in updateUser", error); console.error("Error in updateUser", error);
// P2025 = Record to update not found // P2025 = Record to update not found
if (error.code === "P2025") { if (error.code === "P2025") {
return { success: false, error: "User not found" }; return { success: false, status: 404, error: "User not found" };
} }
// P2002 = Unique Constraint Violation (username) // P2002 = Unique Constraint Violation (username)
if (error.code === "P2002") { if (error.code === "P2002") {
return { success: false, error: "Username already exists" }; return { success: false, status: 409, error: "Username already exists" };
} }
return { success: false, error: "Error while updating User" }; return { success: false, status: 500, error: "Error while updating User" };
} }
} }
@@ -182,7 +182,7 @@ export async function updateUser(
* DeleteUser * DeleteUser
* Deletes an existing user and returns the deleted user * Deletes an existing user and returns the deleted user
* @param id - ID indicatin the user * @param id - ID indicatin the user
* @returns {"success": boolean, "user": {"id": number, "username": string, "role": string}} * @returns {"success": boolean, "status":number, "user": {"id": number, "username": string, "role": string}}
*/ */
export async function deleteUser(id: number) { export async function deleteUser(id: number) {
try { try {
@@ -195,14 +195,14 @@ export async function deleteUser(id: number) {
} }
}); });
return { success: true, user }; return { success: true, status: 200, user };
} catch (error) { } catch (error) {
console.error("Error in deleteUser", error); console.error("Error in deleteUser", error);
// P2025 = Record to update not found // P2025 = Record to update not found
if (error.code === "P2025") { if (error.code === "P2025") {
return { success: false, error: "User not found" }; return { success: false, status: 404, error: "User not found" };
} }
return { success: false, error: "Error while deleting User" }; return { success: false, status: 500, error: "Error while deleting User" };
} }
} }
+12
View File
@@ -0,0 +1,12 @@
export function parseInt(rawInteger){
const integer = Number.parseInt(rawInteger);
if (Number.isNaN(integer) || !Number.isInteger(integer)) {
return null;
}
else {
return 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 [];
}
}
+2471 -14
View File
File diff suppressed because it is too large. Load diff
+26 -5
View File
@@ -1,12 +1,16 @@
{ {
"name": "psalm-talel", "name": "psalm-tafel",
"version": "0.0.5", "version": "0.0.5.1",
"private": true, "private": true,
"scripts": { "scripts": {
"dev": "next dev", "dev": "next dev",
"build": "next build", "build": "next build",
"start": "next start", "start": "next start",
"lint": "eslint" "lint": "eslint",
"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": { "dependencies": {
"@prisma/adapter-better-sqlite3": "^7.9.1", "@prisma/adapter-better-sqlite3": "^7.9.1",
@@ -15,14 +19,27 @@
"argon2": "^0.45.1", "argon2": "^0.45.1",
"better-sqlite3": "^13.0.2", "better-sqlite3": "^13.0.2",
"dotenv": "^17.4.2", "dotenv": "^17.4.2",
"gray-matter": "^4.0.3",
"next": "16.2.9", "next": "16.2.9",
"next-mdx-remote": "^6.0.0",
"papaparse": "^5.5.4", "papaparse": "^5.5.4",
"prisma": "^7.9.1", "prisma": "^7.9.1",
"react": "19.2.4", "react": "19.2.4",
"react-dom": "19.2.4" "react-dom": "19.2.4",
"rehype-autolink-headings": "^7.1.0",
"rehype-highlight": "^7.0.2",
"rehype-pretty-code": "^0.14.5",
"rehype-slug": "^6.0.0",
"rehype-stringify": "^10.0.1",
"remark": "^15.0.1",
"remark-html": "^16.0.1",
"remark-parse": "^11.0.0",
"remark-rehype": "^11.1.2",
"shiki": "^4.4.1"
}, },
"devDependencies": { "devDependencies": {
"@tailwindcss/postcss": "^4", "@tailwindcss/postcss": "^4",
"@tailwindcss/typography": "^0.5.20",
"@types/better-sqlite3": "^7.6.13", "@types/better-sqlite3": "^7.6.13",
"@types/node": "^20", "@types/node": "^20",
"@types/react": "^19", "@types/react": "^19",
@@ -30,7 +47,7 @@
"eslint": "^9", "eslint": "^9",
"eslint-config-next": "16.2.9", "eslint-config-next": "16.2.9",
"tailwindcss": "^4", "tailwindcss": "^4",
"typescript": "^5" "typescript": "^5.9.3"
}, },
"pnpm": { "pnpm": {
"onlyBuiltDependencies": [ "onlyBuiltDependencies": [
@@ -38,5 +55,9 @@
"sharp", "sharp",
"unrs-resolver" "unrs-resolver"
] ]
},
"allowScripts": {
"better-sqlite3@13.0.2": true,
"better-sqlite3@12.11.1": true
} }
} }
-5536
View File
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,17 @@
-- RedefineTables
PRAGMA defer_foreign_keys=ON;
PRAGMA foreign_keys=OFF;
CREATE TABLE "new_SongBookSongs" (
"songBookId" INTEGER NOT NULL,
"songId" INTEGER NOT NULL,
"songNumber" TEXT NOT NULL,
PRIMARY KEY ("songBookId", "songId"),
CONSTRAINT "SongBookSongs_songId_fkey" FOREIGN KEY ("songId") REFERENCES "Song" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT "SongBookSongs_songBookId_fkey" FOREIGN KEY ("songBookId") REFERENCES "SongBook" ("id") ON DELETE CASCADE ON UPDATE CASCADE
);
INSERT INTO "new_SongBookSongs" ("songBookId", "songId", "songNumber") SELECT "songBookId", "songId", "songNumber" FROM "SongBookSongs";
DROP TABLE "SongBookSongs";
ALTER TABLE "new_SongBookSongs" RENAME TO "SongBookSongs";
PRAGMA foreign_keys=ON;
PRAGMA defer_foreign_keys=OFF;
+1 -1
View File
@@ -35,7 +35,7 @@ model SongBook {
model SongBookSongs { model SongBookSongs {
songBookId Int songBookId Int
songId Int songId Int
songNumber Int songNumber String
song Song @relation(fields: [songId], references: [id], onDelete: Cascade) song Song @relation(fields: [songId], references: [id], onDelete: Cascade)
book SongBook @relation(fields: [songBookId], references: [id], onDelete: Cascade) book SongBook @relation(fields: [songBookId], references: [id], onDelete: Cascade)
+10
View File
@@ -0,0 +1,10 @@
export interface ApiMethod {
method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | string;
description: string;
}
export interface ApiRoute {
category: string;
route: string;
methods: ApiMethod[];
}