Compare commits

..
Author SHA1 Message Date
Rudi d7ade96371 Update dockerfile build 2026-10-13 19:42:07 +02:00
Rudi 5a56245218 Update API Doc 2026-10-13 19:26:56 +02:00
Rudi 5d6d8f15f3 delete old files 2026-10-13 19:05:05 +02:00
Rudi 1d1976ed07 delete old files 2026-10-13 19:03:28 +02:00
Rudi 14b8a0c65f API route and script 2026-10-13 19:01:57 +02:00
Rudi df9143e95c added api route 2026-10-13 19:01:31 +02:00
Rudi c234c28d15 openapi.json generate script added 2026-10-13 19:01:22 +02:00
Rudi 87801c5b9b Added a script, to generate openapi.json 2026-10-13 18:59:05 +02:00
Rudi bdc864cf94 Working on Standartisation.... #TODO 2026-08-27 18:07:42 +02:00
Rudi da4d67ea47 Added stream API 2026-08-27 17:00:38 +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
43 changed files with 15011 additions and 7354 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" \
+2 -2
View File
@@ -11,13 +11,13 @@ COPY package.json pnpm-lock.yaml* pnpm-workspace.yaml* ./
RUN apk add --no-cache python3 make g++ RUN apk add --no-cache python3 make g++
# Installation mit deiner funktionierenden Workspace-Konfiguration # Installation mit deiner funktionierenden Workspace-Konfiguration
RUN pnpm i --frozen-lockfile RUN npm i --frozen-lockfile
FROM base AS builder FROM base AS builder
WORKDIR /app WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules COPY --from=deps /app/node_modules ./node_modules
COPY . . COPY . .
RUN pnpm run build RUN npm run openapi:generate; npm run build
FROM base AS runner FROM base AS runner
WORKDIR /app WORKDIR /app
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)
--- ---
+25
View File
@@ -0,0 +1,25 @@
// @/app/api/docs/api/routes.ts
/**
* @openapi
* /api/docs/api:
* get:
* summary: OpenAPI-Spezifikation abrufen
* tags:
* - Docs
* description: Gibt die vollständige OpenAPI-JSON-Spezifikation der API zurück.
* responses:
* 200:
* description: Erfolgreich generierte OpenAPI-Spezifikation.
* content:
* application/json:
* schema:
* type: object
*/
import { NextResponse } from 'next/server';
import spec from '@/src/generated/openapi.json';
export function GET() {
return NextResponse.json(spec);
}
+207
View File
@@ -0,0 +1,207 @@
// @/app/api/songbooks/[songBookId]/route.ts
import { NextResponse } from "next/server";
import { getSongBookById, updateSongBook, deleteSongBook } from "@/lib/db/songbook";
interface RouteParams {
params: Promise<{
songBookId: string;
}>;
};
/**
* @openapi
* /api/songbooks/{songBookId}:
* get:
* summary: Einzelnes Songbook abrufen
* tags:
* - Songbooks
* parameters:
* - in: path
* name: songBookId
* required: true
* schema:
* type: integer
* description: Die ID des Songbooks
* example: 1
* responses:
* 200:
* description: Songbook erfolgreich gefunden
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/SongBook'
* 400:
* description: Ungültige Songbook-ID
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
* 404:
* description: Songbook nicht gefunden
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
* 500:
* description: Serverfehler
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
*/
export async function GET(_request: Request, { params }: RouteParams) {
try {
const { songBookId } = await params;
const res = await getSongBookById(parseInt(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/{songBookId}:
* patch:
* summary: Songbook aktualisieren
* tags:
* - Songbooks
* parameters:
* - in: path
* name: songBookId
* required: true
* schema:
* type: integer
* description: Die ID des Songbooks
* example: 1
* requestBody:
* required: true
* content:
* application/json:
* schema:
* type: object
* properties:
* title:
* type: string
* example: "Feiert Jesus 1"
* language:
* type: string
* example: "DE"
* responses:
* 200:
* description: Songbook erfolgreich aktualisiert
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/SongBook'
* 400:
* description: Ungültige Parameter oder Daten
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
* 404:
* description: Songbook nicht gefunden
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
* 500:
* description: Serverfehler
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
*/
export async function PATCH(request: Request, { params }: RouteParams) {
try {
const { songBookId } = await params;
const data = await request.json();
const res = await updateSongBook(parseInt(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 Aktualisieren des Songbooks" },
{ status: 500 }
);
}
}
/**
* @openapi
* /api/songbooks/{songBookId}:
* delete:
* summary: Songbook löschen
* tags:
* - Songbooks
* parameters:
* - in: path
* name: songBookId
* required: true
* schema:
* type: integer
* description: Die ID des Songbooks
* example: 1
* responses:
* 200:
* description: Songbook erfolgreich gelöscht (gibt das gelöschte Songbook zurück)
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/SongBook'
* 400:
* description: Ungültige Songbook-ID
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
* 404:
* description: Songbook nicht gefunden
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
* 500:
* description: Serverfehler
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
*/
export async function DELETE(_request: Request, { params }: RouteParams) {
try {
const { songBookId } = await params;
const res = await deleteSongBook(parseInt(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 Löschen des Songbooks" },
{ status: 500 }
);
}
}
@@ -0,0 +1,252 @@
// @/app/api/songbooks/[songBookId]/songs/[songId]/route.ts
import { NextResponse } from "next/server";
import { addSongToBook, updateSongInBook, removeSongFromBook } from "@/lib/db/songbooksongs";
interface RouteParams {
params: Promise<{
songBookId: string;
songId: string;
}>;
};
/**
* @openapi
* /api/songbooks/{songBookId}/songs/{songId}:
* post:
* summary: Song zu Liederbuch hinzufügen
* tags:
* - Songbooks
* parameters:
* - in: path
* name: songBookId
* required: true
* schema:
* type: integer
* description: Die ID des Liederbuchs
* example: 1
* - in: path
* name: songId
* required: true
* schema:
* type: integer
* description: Die ID des Songs
* example: 1
* requestBody:
* required: true
* content:
* application/json:
* schema:
* type: object
* required:
* - number
* properties:
* number:
* type: string
* example: "104a"
* description: Die Songnummer im Liederbuch
* responses:
* 200:
* description: Song erfolgreich zugewiesen
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/SongBookEntry'
* 400:
* description: Ungültige Parameter oder fehlende Songnummer
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
* 409:
* description: Songnummer bereits vergeben oder Song existiert bereits im Buch
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
* 500:
* description: Serverfehler
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
*/
export async function POST(request: Request, { params }: RouteParams) {
try {
const { songBookId, songId } = await params;
const data = await request.json();
const res = await addSongToBook(parseInt(songId), parseInt(songBookId), String(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 Zuweisen des Songs" },
{ status: 500 }
);
}
}
/**
* @openapi
* /api/songbooks/{songBookId}/songs/{songId}:
* patch:
* summary: Songnummer eines Songs im Liederbuch aktualisieren
* tags:
* - Songbooks
* parameters:
* - in: path
* name: songBookId
* required: true
* schema:
* type: integer
* description: Die ID des Liederbuchs
* example: 1
* - in: path
* name: songId
* required: true
* schema:
* type: integer
* description: Die ID des Songs
* example: 1
* requestBody:
* required: true
* content:
* 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
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/SongBookEntry'
* 400:
* description: Ungültige Parameter oder fehlende Daten
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
* 404:
* description: Zuweisung nicht gefunden
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
* 409:
* description: Neue Songnummer bereits vergeben
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
* 500:
* description: Serverfehler
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
*/
export async function PATCH(request: Request, { params }: RouteParams) {
try {
const { songBookId, songId } = await params;
const data = await request.json();
const res = await updateSongInBook(parseInt(songId), parseInt(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 Aktualisieren der Songnummer" },
{ status: 500 }
);
}
}
/**
* @openapi
* /api/songbooks/{songBookId}/songs/{songId}:
* delete:
* summary: Song aus Liederbuch entfernen
* tags:
* - Songbooks
* parameters:
* - in: path
* name: songBookId
* required: true
* schema:
* type: integer
* description: Die ID des Liederbuchs
* example: 1
* - in: path
* name: songId
* required: true
* schema:
* type: integer
* description: Die ID des Songs
* example: 1
* responses:
* 200:
* description: Song erfolgreich aus dem Liederbuch entfernt (gibt die entfernte Zuweisung zurück)
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/SongBookEntry'
* 400:
* description: Ungültige Parameter
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
* 404:
* description: Zuweisung nicht gefunden
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
* 500:
* description: Serverfehler
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
*/
export async function DELETE(_request: Request, { params }: RouteParams) {
try {
const { songBookId, songId } = await params;
const res = await removeSongFromBook(parseInt(songId), parseInt(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 Entfernen des Songs" },
{ status: 500 }
);
}
}
@@ -0,0 +1,91 @@
// @/app/api/songbooks/[songBookId]/songs/route.ts
import { NextResponse } from "next/server";
import { getSongByNumber } from "@/lib/db/songbooksongs";
interface RouteParams {
params: Promise<{
songBookId: string;
}>;
};
/**
* @openapi
* /api/songbooks/{songBookId}/songs:
* get:
* summary: Einen Song nach Nummer in einem Songbook suchen
* tags:
* - Songbooks
* parameters:
* - in: path
* name: songBookId
* required: true
* schema:
* type: integer
* description: Die ID des Songbooks
* example: 1
* - in: query
* name: number
* required: true
* schema:
* type: string
* description: Die Nummer des Songs im Songbook
* example: "123"
* - in: query
* name: n
* required: false
* schema:
* type: string
* description: Alias für `number`
* example: "123"
* responses:
* 200:
* description: Song im Songbook erfolgreich gefunden
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/SongBookEntry'
* 400:
* description: Ungültige Songbook-ID oder fehlender number-Parameter
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
* 404:
* description: Songbook oder Song nicht gefunden
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
* 500:
* description: Serverfehler
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
*/
export async function GET(request: Request, { params }: RouteParams) {
try {
const { songBookId } = await params;
const { searchParams } = new URL(request.url);
const number = searchParams.get("number") || searchParams.get("n");
if(number){
const res = await getSongByNumber(parseInt(songBookId), number);
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 }
);
}
}
+150 -12
View File
@@ -1,27 +1,165 @@
// @/app/api/songbooks/route.ts
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 or search songbooks by title
* tags:
* - Songbooks
* parameters:
* - in: query
* name: query
* required: false
* schema:
* type: string
* description: Search term for the songbook title
* example: "Feiert Jesus"
* - in: query
* name: q
* required: false
* schema:
* type: string
* description: Alias for `query`
* example: "Feiert Jesus"
* responses:
* 200:
* description: List of songbooks (filtered by title if a query is given)
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: '#/components/schemas/SongBook'
* 500:
* description: Internal Server Error
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
*/
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");
// 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 });
}
// 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 });
} catch (error) { } catch (error) {
return NextResponse.json({ success: false, message: error}, { 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
* tags:
* - Songbooks
* requestBody:
* required: true
* content:
* application/json:
* schema:
* type: object
* required:
* - title
* - language
* 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:
* $ref: '#/components/schemas/SongBook'
* 400:
* description: Bad Request (missing title or language)
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
* 409:
* description: Conflict (title already exists)
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
* 500:
* description: Internal Server Error
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
*/
export async function POST(request: Request) { export async function POST(request: Request) {
try { try {
const { name, language } = await request.json(); const data = await request.json();
if (!name ) { if (!data.title || !data.language) {
return NextResponse.json({ success: false, message: "Fields incomplete (name)"}, { status: 400 }) return NextResponse.json(
{ message: "Field 'title' and 'language' are required" },
{ status: 400 }
);
} }
const newBook = await addSongbook(String(name), String(language)) const res = await createSongBook(data);
if (!res.success) {
return NextResponse.json(
{ message: res.error },
{ status: res.status }
);
}
return NextResponse.json(res, { status: res.status });
return NextResponse.json(newBook, { status: 201 })
} catch (error) { } catch (error) {
return NextResponse.json({ success: false }, { status: 500 }) 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 }
);
}
}
+203
View File
@@ -0,0 +1,203 @@
// @/app/api/songs/[songId]/route.ts
import { NextResponse } from "next/server";
import { getSongById, updateSong, deleteSong } from "@/lib/db/song";
interface RouteParams {
params: Promise<{
songId: string;
}>;
};
/**
* @openapi
* /api/songs/{songId}:
* get:
* summary: Einzelnen Song abrufen
* tags:
* - Songs
* parameters:
* - in: path
* name: songId
* required: true
* schema:
* type: integer
* description: Die ID des Songs
* example: 1
* responses:
* 200:
* description: Song erfolgreich gefunden
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Song'
* 400:
* description: Ungültige Song-ID
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
* 404:
* description: Song nicht gefunden
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
* 500:
* description: Serverfehler
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
*/
export async function GET(_request: Request, { params }: RouteParams) {
try {
const { songId } = await params;
const res = await getSongById(parseInt(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/{songId}:
* patch:
* summary: Song aktualisieren
* tags:
* - Songs
* parameters:
* - in: path
* name: songId
* required: true
* schema:
* type: integer
* description: Die ID des Songs
* example: 1
* requestBody:
* required: true
* content:
* application/json:
* schema:
* type: object
* properties:
* title:
* type: string
* example: "Großer Gott"
* responses:
* 200:
* description: Song erfolgreich aktualisiert
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Song'
* 400:
* description: Ungültige Parameter oder Daten
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
* 404:
* description: Song nicht gefunden
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
* 500:
* description: Serverfehler
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
*/
export async function PATCH(request: Request, { params }: RouteParams) {
try {
const { songId } = await params;
const data = await request.json();
const res = await updateSong(parseInt(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 Aktualisieren des Songs" },
{ status: 500 }
);
}
}
/**
* @openapi
* /api/songs/{songId}:
* delete:
* summary: Song löschen
* tags:
* - Songs
* parameters:
* - in: path
* name: songId
* required: true
* schema:
* type: integer
* description: Die ID des Songs
* example: 1
* responses:
* 200:
* description: Song erfolgreich gelöscht (gibt den gelöschten Song zurück)
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Song'
* 400:
* description: Ungültige Song-ID
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
* 404:
* description: Song nicht gefunden
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
* 500:
* description: Serverfehler
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
*/
export async function DELETE(_request: Request, { params }: RouteParams) {
try {
const { songId } = await params;
const res = await deleteSong(parseInt(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 Löschen des Songs" },
{ 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 }
);
}
}
+146 -20
View File
@@ -1,31 +1,157 @@
// @/app/api/songs/route.ts
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"; /**
* @openapi
export async function GET() { * /api/songs:
const songs = await getSongs(); * get:
if (songs) { * summary: Get all songs or search songs by title
return NextResponse.json(songs); * tags:
} else { * - Songs
return NextResponse.json({ success: false}, { status: 500}) * parameters:
} * - in: query
} * name: query
export async function POST(request: Request) { * required: false
* schema:
* type: string
* description: Search term for the song title
* example: "Großer Gott"
* - in: query
* name: q
* required: false
* schema:
* type: string
* description: Alias for `query`
* example: "Großer Gott"
* responses:
* 200:
* description: List of songs (filtered by title if a query is given)
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: '#/components/schemas/Song'
* 500:
* description: Internal Server Error
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/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) { if (query) {
return NextResponse.json({ success: false, message: "Fields incomplete"}, { status: 400 }); 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 });
} }
const result = await addSongToSongbook(title, Number(songbookId), String(number)); return NextResponse.json(res.songBooks, { status: res.status });
if (result.success) {
return NextResponse.json({ success: true });
} else {
return NextResponse.json({ success: false }, { status: 500 });
} }
// Ansonsten alle Songs abrufen
const res = await getSongs();
if (!res.success) {
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("GET /api/songs error:", error);
return NextResponse.json(
{ message: "Internal Server Error" },
{ status: 500 }
);
}
}
/**
* @openapi
* /api/songs:
* post:
* summary: Creates a new song
* tags:
* - Songs
* requestBody:
* required: true
* content:
* application/json:
* schema:
* type: object
* required:
* - title
* properties:
* title:
* type: string
* example: "Großer Gott"
* responses:
* 201:
* description: Song successfully created
* content:
* application/json:
* schema:
* type: object
* properties:
* success:
* type: boolean
* example: true
* song:
* $ref: '#/components/schemas/Song'
* 400:
* description: Bad Request (missing title)
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
* 409:
* description: Conflict (title already exists)
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
* 500:
* description: Internal Server Error
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
*/
export async function POST(request: Request) {
try {
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 },
{ 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 }
);
} }
} }
-48
View File
@@ -1,48 +0,0 @@
import { NextResponse } from "next/server";
import { getSong } from "@/lib/db/managing";
let currentSong = {
songID: "",
songbook: "",
number: "",
title: ""
};
export async function GET() {
return NextResponse.json(currentSong)
}
export async function POST(request: Request) {
try {
const data = await request.json();
const songID = data.songID;
const songbookID = data.songbookID;
if (!songID || !songbookID) {
return NextResponse.json({ success: false, error: "Fields incomplete!" }, { status: 400 });
}
const song = await getSong(Number(songbookID), String(songID));
if (song) {
currentSong = {
songID: String(songID),
songbook: song.songbook_name,
number: song.number,
title: song.song_title,
};
} else {
currentSong = {
songID: "",
songbook: "",
number: "",
title: "",
};
}
console.log(currentSong);
return NextResponse.json({ success: true });
} catch (error) {
return NextResponse.json({ success: false, error: "Server-Fehler" }, { status: 500 });
}
}
+161
View File
@@ -0,0 +1,161 @@
// @/app/api/stream/route.ts
import { NextResponse } from "next/server";
/**
* @openapi
* components:
* schemas:
* StreamError:
* type: object
* properties:
* success:
* type: boolean
* example: false
* error:
* type: string
* example: "Fields incomplete!"
*/
let currentSong = {
number: "",
song: "",
songbook: "",
};
const clients = new Set<ReadableStreamDefaultController>();
/**
* @openapi
* /api/stream:
* get:
* summary: Aktuell gestreamtes Lied abrufen (Server-Sent Events)
* description: Öffnet einen SSE-Stream. Beim Verbinden wird das aktuelle Lied gesendet (falls gesetzt), danach bei jeder Änderung ein neues Event.
* tags:
* - Stream
* responses:
* 200:
* description: Event-Stream mit dem aktuellen Lied
* content:
* text/event-stream:
* schema:
* type: string
* example: 'data: {"number":"104a","song":"Großer Gott","songbook":"Feiert Jesus 1"}'
*/
export async function GET() {
let controllerRef: ReadableStreamDefaultController;
const stream = new ReadableStream({
start(controller) {
controllerRef = controller;
clients.add(controller);
if (currentSong.song) {
controller.enqueue(`data: ${JSON.stringify(currentSong)}\n\n`);
}
},
cancel() {
clients.delete(controllerRef);
},
});
return new NextResponse(stream, {
headers: {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive',
},
});
}
/**
* @openapi
* /api/stream:
* post:
* summary: Lied zum Streamen festlegen
* description: Setzt das aktuelle Lied und sendet es an alle verbundenen Stream-Clients.
* tags:
* - Stream
* requestBody:
* required: true
* content:
* application/json:
* schema:
* type: object
* required:
* - song
* - songBook
* - number
* properties:
* song:
* type: string
* example: "Großer Gott"
* songBook:
* type: string
* example: "Feiert Jesus 1"
* number:
* type: string
* example: "104a"
* responses:
* 200:
* description: Lied gesetzt und an alle Clients gesendet
* content:
* application/json:
* schema:
* type: object
* properties:
* success:
* type: boolean
* example: true
* currentSong:
* type: object
* properties:
* number:
* type: string
* example: "104a"
* song:
* type: string
* example: "Großer Gott"
* songbook:
* type: string
* example: "Feiert Jesus 1"
* 400:
* description: Felder unvollständig
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/StreamError'
* 500:
* description: Serverfehler
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/StreamError'
*/
export async function POST(request: Request) {
try {
const data = await request.json();
const song = data.song?.trim() ?? null;
const songbook = data.songBook?.trim() ?? null;
const number = data.number?.trim() ?? null;
if (song == null || songbook == null || number == null) {
return NextResponse.json({ success: false, error: "Fields incomplete!" }, { status: 400 });
}
currentSong = {
song,
songbook,
number
};
clients.forEach((controller) => {
controller.enqueue(`data: ${JSON.stringify(currentSong)}\n\n`);
});
return NextResponse.json({ success: true , currentSong }, { status: 200 });
} catch (error) {
return NextResponse.json({ success: false, error: "Server-Fehler" }, { status: 500 });
}
}
+8
View File
@@ -0,0 +1,8 @@
'use client';
import SwaggerUI from 'swagger-ui-react';
import 'swagger-ui-react/swagger-ui.css';
export default function DocsPage() {
return <SwaggerUI url="/api/docs/api" />;
}
+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;
}
+108 -13
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"> >
{/* 1. Liederbuch */}
<header className="w-full flex-[1.5] flex items-center justify-center overflow-hidden py-1">
<svg viewBox="0 0 1000 200" className="w-full h-full max-h-full">
<text
x="50%"
y="50%"
dominantBaseline="central"
textAnchor="middle"
className="fill-amber-300 font-black uppercase"
fontSize="220"
>
{songbook} {songbook}
</span> </text>
</div> </svg>
<div className="flex-1 flex items-center justify-center w-full"> </header>
<h1 className="text-[14rem] md:text-[20rem] font-black leading-none tracking-tighter text-white">
{/* 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} {number}
</h1> </text>
</div> </svg>
<div className="w-full text-center pb-2 px-4"> </main>
<p className="text-3xl md:text-6xl font-medium text-neutral-400 truncate">
{/* 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} {title}
</p> </text>
</div> </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>
);
}
+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>
);
}
+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);
}
+42
View File
@@ -0,0 +1,42 @@
export interface Song {
id: number;
title: string;
}
export interface SongBook {
id: number;
title: string;
language?: string;
}
export interface SongDetailed {
song: {
id: number;
title: string;
songBooks?:{songNumber: number; book:SongBook}[]
};
}
export type APIResponse<T> =
| { success: true; status: number; data: T }
| { success: false; status: number; error: string };
export type GetSongsResponse = APIResponse<Song[]>;
export type GetSongDetailedResponse =
| {
success: true;
status: number;
song: SongDetailed
}
| { success: false; status: number; error: string };
export type GetSongsDelailedResponse =
| {
success: true;
status: number;
songs: SongDetailed[]
}
| { success: false; status: number; error: string };
export type CreateSongsResponse = APIResponse<Song>;
+58 -35
View File
@@ -1,14 +1,22 @@
import { prisma } from "@/lib/db/prisma"; import { prisma } from "@/lib/db/prisma";
import { parseInt } from "@/lib/helper/checkvar";
import type * as API from "./response";
// For Error checking use this import: import { Prisma } from "@prisma/client"; // For Error checking use this import: import { Prisma } from "@prisma/client";
interface Response {
success: boolean;
status: number;
songs?: [];
error?: string;
}
/** /**
* 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(): Promise<API.GetSongsResponse> {
try{ try{
const songs = await prisma.song.findMany({ const songs = await prisma.song.findMany({
select: { select: {
@@ -20,10 +28,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 +40,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): Promise<API.GetSongDetailedResponse> {
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 +58,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 +69,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,20 +85,19 @@ 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 {"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): Promise<API.GetSongsDelailedResponse> {
try { try {
const cleanQuery = query.trim(); const cleanQuery = query.trim();
if (!cleanQuery) { if (!cleanQuery) {
return { success: true, songBooks: [] }; return { success: true, status: 200, songs: [] };
} }
const songs = await prisma.song.findMany({ const songs = await prisma.song.findMany({
where: { where: {
title: { title: {
contains: query.trim(), contains: query.trim(),
mode: "insensitive", // Textsearch
}, },
}, },
select: { select: {
@@ -106,10 +118,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 +129,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 }): Promise<API.CreateSongsResponse> {
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 +147,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 +166,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 }
) { ): Promise<API.CreateSongsResponse> {
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 +186,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 +198,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 +218,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): Promise<API.CreateSongsResponse> {
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 +234,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: number){
const integer = Number.parseInt(rawInteger);
if (Number.isNaN(integer) || !Number.isInteger(integer)) {
return null;
}
else {
return integer;
}
}
+11273 -1426
View File
File diff suppressed because it is too large. Load diff
+30 -8
View File
@@ -1,36 +1,54 @@
{ {
"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",
"openapi:generate": "node scripts/generate-openapi.mjs"
}, },
"dependencies": { "dependencies": {
"@prisma/adapter-better-sqlite3": "^7.9.1", "@prisma/adapter-better-sqlite3": "^7.9.1",
"@prisma/client": "^7.9.1", "@prisma/client": "^7.10.0",
"@types/papaparse": "^5.5.2", "@types/papaparse": "^5.5.2",
"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",
"next": "16.2.9", "gray-matter": "^4.0.3",
"next": "^16.4.0",
"next-mdx-remote": "^6.0.0",
"papaparse": "^5.5.4", "papaparse": "^5.5.4",
"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",
"swagger-ui-react": "^5.33.2"
}, },
"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",
"@types/react-dom": "^19", "@types/react-dom": "^19",
"@types/swagger-jsdoc": "^6.0.4",
"@types/swagger-ui-react": "^5.18.0",
"eslint": "^9", "eslint": "^9",
"eslint-config-next": "16.2.9", "eslint-config-next": "16.2.9",
"prisma": "^8.0.0-rc.22",
"swagger-jsdoc": "^6.3.0",
"tailwindcss": "^4", "tailwindcss": "^4",
"typescript": "^5" "typescript": "^5.9.3"
}, },
"pnpm": { "pnpm": {
"onlyBuiltDependencies": [ "onlyBuiltDependencies": [
@@ -38,5 +56,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)
+18
View File
@@ -0,0 +1,18 @@
import swaggerJsdoc from 'swagger-jsdoc';
import { mkdirSync, writeFileSync } from 'node:fs';
import { dirname } from 'node:path';
const spec = swaggerJsdoc({
definition: {
openapi: '3.0.0',
info: { title: 'PsalmTafel API', version: '1.0.0' },
},
apis: ['./app/api/**/*.ts'],
failOnErrors: true,
});
const out = 'src/generated/openapi.json';
mkdirSync(dirname(out), { recursive: true });
writeFileSync(out, JSON.stringify(spec, null, 2));
console.log(`OpenAPI: ${Object.keys(spec.paths ?? {}).length} Pfade -> ${out}`);
File diff suppressed because it is too large. Load diff
+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[];
}