Compare commits

..
Author SHA1 Message Date
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
15 changed files with 216 additions and 177 deletions

No files matched your search

-1
View File
@@ -46,4 +46,3 @@ songs.sqlite
.gitignore
/lib/generated/prisma
pnpm-lock.yaml
+3 -2
View File
@@ -2,6 +2,7 @@
import { error } from "console";
import Papa from "papaparse";
import { addSongToSongbook } from "@/lib/db/managing";
interface CSVRow {
nummer: string;
@@ -30,8 +31,8 @@ export async function uploadCSVAction(formData:FormData) {
console.log("Data:", rows);
rows.forEach(row => {
console.log(`Nummer: ${row.nummer}, Titel: ${row.titel}`);
//addSongToSongbook(String(row.titel), Number(songbookId), String(row.nummer))
//console.log(`Nummer: ${row.number}, Titel: ${row.titel}`);
addSongToSongbook(String(row.titel), Number(songbookId), String(row.nummer))
});
return { success: true, message: `${rows.length} Zeilen erfolgreich importiert.`};
+31 -42
View File
@@ -9,7 +9,7 @@ import { Screens } from "@/components/DatabaseOverview";
interface Songbook {
id: number;
title: string;
name: string;
language: string;
}
@@ -22,7 +22,7 @@ interface Song {
interface SongInfo {
songbook_id: number;
songbook_title: string;
songbook_name: string;
song_number: string;
title: string;
}
@@ -34,7 +34,7 @@ export default function AdminPage() {
const [number, setNumber] = useState("");
const [title, setTitle] = useState("");
const [newBookTitle, setNewBookTitle] = useState("");
const [newBookName, setNewBookName] = useState("");
const [newBookLanguage, setNewBookLanguage] = useState("");
const [uploadStatus, setUploadStatus] = useState<string | null>(null);
@@ -96,34 +96,21 @@ export default function AdminPage() {
}
try {
// Create song
const res1 = await fetch("/api/songs", {
const res = await fetch("/api/songs", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
songbookId: Number(selectedSongbookId),
number: number,
title: title
})
})
if (res1.ok) {
console.log("Lied erfolgreich erstellt!");
});
if (res.ok) {
alert("Lied erfolgreich hinzugefügt!");
setNumber("");
setTitle("");
} else {
console.log("Lied erstellen fehlgeschlagen!");
}
// Attach song to songbook
const data = await res1.json()
const songId = data.song.id;
const res2 = await fetch(`/api/songbooks/${Number(selectedSongbookId)}/songs/${songId}`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
number: number
})
})
if (res2.ok) {
console.log("Lied erfolgreich dem Liederbuch zugewiesen!");
} else {
console.log("Fehler");
alert("Fehler beim Senden.");
}
} catch (error) {
console.error("Failed sending current songID:", error);
@@ -137,17 +124,19 @@ export default function AdminPage() {
}
try {
const res2 = await fetch(`/api/songbooks/${Number(selectedSongbookId)}/songs/${selectedSong.song_id}`, {
const res = await fetch("/api/songs/attach", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
number: number
songbookId: selectedSongbookId,
songId: selectedSong.song_id,
number: number,
})
})
if (res2.ok) {
console.log("Lied erfolgreich dem Liederbuch zugewiesen!");
});
if (res.ok) {
alert("Lied erfolgreich zum Liederbuch hinzugefügt!");
} else {
console.log("Fehler");
alert("Fehler beim Senden.");
}
} catch (error) {
console.error("Failed sending current songID:", error);
@@ -180,8 +169,8 @@ export default function AdminPage() {
}
const addSongbook = async () => {
if (!newBookTitle) {
alert("Der Title des Liederbuches darf nicht leer sein!");
if (!newBookName) {
alert("Der Name des Liederbuches darf nicht leer sein!");
return;
}
@@ -189,14 +178,14 @@ export default function AdminPage() {
const res = await fetch("/api/songbooks", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ title: newBookTitle, language: newBookLanguage })
body: JSON.stringify({ name: newBookName, language: newBookLanguage })
});
if (res.ok) {
const createdBook = await res.json();
setSongbooks([...songbooks, createdBook]);
alert("Liederbuch erfolgreich erstellt!");
setNewBookTitle("");
setNewBookName("");
setNewBookLanguage("");
} else {
alert("Failed adding songbook!");
@@ -226,8 +215,8 @@ export default function AdminPage() {
<Input.Text
type="text"
placeholder="z.B. Gesangbuch"
value={newBookTitle}
onChange={(e) => setNewBookTitle(e.target.value)}
value={newBookName}
onChange={(e) => setNewBookName(e.target.value)}
/>
</div>
<div>
@@ -259,7 +248,7 @@ export default function AdminPage() {
<option value="">-- Bitte wählen --</option>
{songbooks.map((book) => (
<option key={book.id} value={String(book.id)}>
{book.title}{book.language ? ` (${book.language})` : ""}
{book.name}{book.language ? ` (${book.language})` : ""}
</option>
))}
</Input.Select>
@@ -301,7 +290,7 @@ export default function AdminPage() {
<option value="">-- Bitte wählen --</option>
{songbooks.map((book) => (
<option key={book.id} value={String(book.id)}>
{book.title}{book.language ? ` (${book.language})` : ""}
{book.name}{book.language ? ` (${book.language})` : ""}
</option>
))}
</Input.Select>
@@ -346,7 +335,7 @@ export default function AdminPage() {
<ul className="list-disc list-inside pl-2 text-xs text-neutral-400">
{songInfos.map((info) => (
<li key={info.songbook_id}>
{info.songbook_title} (Nr. {info.song_number})
{info.songbook_name} (Nr. {info.song_number})
</li>
))}
</ul>
@@ -367,7 +356,7 @@ export default function AdminPage() {
<option value="">-- Bitte wählen --</option>
{songbooks.map((book) => (
<option key={book.id} value={String(book.id)}>
{book.title}{book.language ? ` (${book.language})` : ""}
{book.name}{book.language ? ` (${book.language})` : ""}
</option>
))}
</Input.Select>
@@ -401,7 +390,7 @@ export default function AdminPage() {
{songInfos.length > 0 ? (
songInfos.map((info) => (
<option key={info.songbook_id} value={String(info.songbook_id)}>
{info.songbook_title} (Nr. {info.song_number})
{info.songbook_name} (Nr. {info.song_number})
</option>
))
): ""}
+12 -7
View File
@@ -1,6 +1,11 @@
import { NextResponse } from "next/server";
import { getSongBookById, updateSongBook, deleteSongBook } from "@/lib/db/songbook";
// import { parseInt } from "@/lib/helper/checkvar";
interface RouteParams {
params: Promise<{
songBookId: string;
}>;
};
/**
* @openapi
@@ -28,12 +33,12 @@ import { getSongBookById, updateSongBook, deleteSongBook } from "@/lib/db/songbo
*/
export async function GET(request: Request, { params }) {
export async function GET(_request: Request, { params }: RouteParams) {
try {
const { songBookId } = await params;
const res = await getSongBookById(songBookId);
const res = await getSongBookById(parseInt(songBookId));
if (!res.success) {
@@ -81,11 +86,11 @@ export async function GET(request: Request, { params }) {
* 500:
* description: Serverfehler
*/
export async function PATCH(request: Request, { params }) {
export async function PATCH(request: Request, { params }: RouteParams) {
try {
const { songBookId } = await params;
const data = await request.json();
const res = await updateSongBook(songBookId, data);
const res = await updateSongBook(parseInt(songBookId), data);
if (!res.success) {
return NextResponse.json({ message: res.error }, { status: res.status });
@@ -126,10 +131,10 @@ export async function PATCH(request: Request, { params }) {
* 500:
* description: Serverfehler
*/
export async function DELETE(request: Request, { params }) {
export async function DELETE(_request: Request, { params }: RouteParams) {
try {
const { songBookId } = await params;
const res = await deleteSongBook(songBookId);
const res = await deleteSongBook(parseInt(songBookId));
if (!res.success) {
return NextResponse.json({ message: res.error }, { status: res.status });
@@ -1,6 +1,12 @@
import { NextResponse } from "next/server";
import { addSongToBook, updateSongInBook, removeSongFromBook } from "@/lib/db/songbooksongs";
// import { parseInt } from "@/lib/helper/checkvar";
interface RouteParams {
params: Promise<{
songBookId: string;
songId: string;
}>;
};
/**
* @openapi
@@ -45,13 +51,13 @@ import { addSongToBook, updateSongInBook, removeSongFromBook } from "@/lib/db/so
* 500:
* description: Serverfehler
*/
export async function POST(request: Request, { params }) {
export async function POST(request: Request, { params }: RouteParams) {
try {
const { songBookId, songId } = await params;
const data = await request.json();
const res = await addSongToBook(songId, songBookId, data.number);
const res = await addSongToBook(parseInt(songId), parseInt(songBookId), String(data.number));
if (!res.success) {
@@ -114,11 +120,11 @@ export async function POST(request: Request, { params }) {
* 500:
* description: Serverfehler
*/
export async function PATCH(request: Request, { params }) {
export async function PATCH(request: Request, { params }: RouteParams) {
try {
const { songBookId, songId } = await params;
const data = await request.json();
const res = await updateSongInBook(songId, songBookId, data);
const res = await updateSongInBook(parseInt(songId), parseInt(songBookId), data);
if (!res.success) {
return NextResponse.json({ message: res.error }, { status: res.status });
@@ -165,11 +171,11 @@ export async function PATCH(request: Request, { params }) {
* 500:
* description: Serverfehler
*/
export async function DELETE(request: Request, { params }) {
export async function DELETE(_request: Request, { params }: RouteParams) {
try {
const { songBookId, songId } = await params;
const res = await removeSongFromBook(songId, songBookId);
const res = await removeSongFromBook(parseInt(songId), parseInt(songBookId));
if (!res.success) {
return NextResponse.json({ message: res.error }, { status: res.status });
@@ -1,6 +1,11 @@
import { NextResponse } from "next/server";
import { getSongByNumber } from "@/lib/db/songbooksongs";
interface RouteParams {
params: Promise<{
songBookId: string;
}>;
};
/**
* @openapi
@@ -26,14 +31,14 @@ import { getSongByNumber } from "@/lib/db/songbooksongs";
* 500:
* description: Serverfehler
*/
export async function GET(request: Request, { params }) {
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(songBookId, number);
const res = await getSongByNumber(parseInt(songBookId), number);
if (!res.success) {
return NextResponse.json({ message: res.error }, { status: res.status });
+11 -7
View File
@@ -1,7 +1,11 @@
import { NextResponse } from "next/server";
import { getSongById, updateSong, deleteSong } from "@/lib/db/song";
// import { parseInt } from "@/lib/helper/checkvar";
interface RouteParams {
params: Promise<{
songId: string;
}>;
};
/**
* @openapi
@@ -27,10 +31,10 @@ import { getSongById, updateSong, deleteSong } from "@/lib/db/song";
* 500:
* description: Serverfehler
*/
export async function GET(request: Request, { params }) {
export async function GET(_request: Request, { params }: RouteParams) {
try {
const { songId } = await params;
const res = await getSongById(songId);
const res = await getSongById(parseInt(songId));
if (!res.success) {
return NextResponse.json({ message: res.error }, { status: res.status });
@@ -77,11 +81,11 @@ export async function GET(request: Request, { params }) {
* 500:
* description: Serverfehler
*/
export async function PATCH(request: Request, { params }) {
export async function PATCH(request: Request, { params }: RouteParams) {
try {
const { songId } = await params;
const data = await request.json();
const res = await updateSong(songId, data);
const res = await updateSong(parseInt(songId), data);
if (!res.success) {
return NextResponse.json({ message: res.error }, { status: res.status });
@@ -122,10 +126,10 @@ export async function PATCH(request: Request, { params }) {
* 500:
* description: Serverfehler
*/
export async function DELETE(request: Request, { params }) {
export async function DELETE(_request: Request, { params }: RouteParams) {
try {
const { songId } = await params;
const res = await deleteSong(songId);
const res = await deleteSong(parseInt(songId));
if (!res.success) {
return NextResponse.json({ message: res.error }, { status: res.status });
+1 -4
View File
@@ -110,10 +110,7 @@ export async function POST(request: Request) {
if (!res.success) {
return NextResponse.json(
{
message: res.error,
song: res.song
},
{ message: res.error },
{ status: res.status }
);
}
-77
View File
@@ -1,77 +0,0 @@
// @wikiCategory: Stream
import { NextResponse } from "next/server";
import { getSongById } from "@/lib/db/song";
let currentSong = {
songID: "",
songbook: "",
number: "",
title: ""
};
// @wikiDescription: Akutell gestreamtes Lied abrufen
export async function GET() {
return NextResponse.json(currentSong)
}
// @wikiDescription: Lied zum Streamen festlegen
export async function POST(request: Request) {
try {
const data = await request.json();
const { songID, songbookID } = data;
if (!songID || !songbookID) {
return NextResponse.json(
{ success: false, error: "Fields incomplete!" },
{ status: 400 }
);
}
const result = await getSongById(songID);
if (result.success && result.song) {
const song = result.song;
// looking for the songbook with matching ID
const matchedBook = song.songBooks.find(
(entry) => String(entry.book.id) === String(songbookID)
);
if (matchedBook) {
currentSong = {
songID: String(song.id),
songbook: matchedBook.book.title,
number: String(matchedBook.songNumber),
title: song.title,
};
} else {
// song does exist but not in the given songbook
currentSong = {
songID: "",
songbook: "",
number: "",
title: "",
};
}
} else {
// song does not exist
currentSong = {
songID: "",
songbook: "",
number: "",
title: "",
};
}
console.log("Aktualisierter currentSong:", currentSong);
return NextResponse.json({ success: true, currentSong });
} catch (error) {
console.error("API POST Error:", error);
return NextResponse.json(
{ success: false, error: "Server-Fehler" },
{ status: 500 }
);
}
}
+67
View File
@@ -0,0 +1,67 @@
// @wikiCategory: Stream
import { NextResponse } from "next/server";
let currentSong = {
number: "",
song: "",
songbook: "",
};
const clients = new Set<ReadableStreamDefaultController>();
// @wikiDescription: Akutell gestreamtes Lied abrufen
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',
},
});
}
// @wikiDescription: Lied zum Streamen festlegen
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 });
}
}
+12 -14
View File
@@ -1,7 +1,7 @@
import { useState, useEffect, ComponentPropsWithoutRef } from "react";
import Card from "./Card";
import { Input } from "./FormElements";
import Card from "./Card"
import { Input } from "./FormElements"
interface SongsProps extends Omit<ComponentPropsWithoutRef<typeof Card>, "title" | "children"> {
onSelectSong?: (song: Song) => void;
@@ -9,7 +9,7 @@ interface SongsProps extends Omit<ComponentPropsWithoutRef<typeof Card>, "title"
}
interface Song {
id: number;
song_id: number;
songbook_id: number;
song_number: string;
title: string;
@@ -17,16 +17,17 @@ interface Song {
interface Songbook {
id: number;
title: string;
name: string;
language: string;
}
function Songs({ actionName = "Auswählen", onSelectSong, className = "", ...props }: SongsProps) {
function Songs({ actionName, onSelectSong, className = "", ...props }: SongsProps) {
const [song_search_name, setSongSearchName] = useState("");
const [searchResults, setSearchResults] = useState<Song[]>([]);
const [allSongs, setAllSongs] = useState<Song[]>([]);
const [songbooks, setSongbooks] = useState<Songbook[]>([]);
const search = (query: string) => {
setSongSearchName(query);
if (query.trim() !== "") {
@@ -52,7 +53,7 @@ function Songs({ actionName = "Auswählen", onSelectSong, className = "", ...pro
}
} catch (error) {
setAllSongs([]);
console.error("Failed fetching songslist!", error);
console.error("Failed fetching songslist!");
}
};
@@ -67,7 +68,6 @@ function Songs({ actionName = "Auswählen", onSelectSong, className = "", ...pro
console.error("Loading songbooks failed: ", error);
}
}
loadSongbooks();
getSongslist();
}, []);
@@ -86,7 +86,6 @@ function Songs({ actionName = "Auswählen", onSelectSong, className = "", ...pro
onChange={(e) => search(e.target.value)}
/>
</div>
{/* TABELLE */}
<div className="flex-1 min-h-0 overflow-auto border border-neutral-200 dark:border-neutral-800 rounded-lg bg-white dark:bg-black">
<table className="w-full text-left border-collapse text-sm">
@@ -106,17 +105,16 @@ function Songs({ actionName = "Auswählen", onSelectSong, className = "", ...pro
) : (
searchResults.map((song) => {
const songBook = songbooks.find((book) => book.id === song.songbook_id);
return (
<tr key={`${song.songbook_id}-${song.id}`} className="hover:bg-neutral-100/60 dark:hover:bg-neutral-900/40 transition">
<tr key={`${song.songbook_id}-${song.song_id}`} className="hover:bg-neutral-100/60 dark:hover:bg-neutral-900/40 transition">
<td className="p-3 font-medium text-neutral-900 dark:text-white max-w-[180px] sm:max-w-none truncate">
{song.title}
<span className="block text-xs text-neutral-500 dark:text-neutral-400 sm:hidden mt-0.5">
{songBook ? songBook.title : "Unbekannt"}
{songBook ? songBook.name : "Unbekannt"}
</span>
</td>
<td className="p-3 text-neutral-700 dark:text-neutral-300 hidden sm:table-cell">
{songBook ? songBook.title : "Unbekannt"}
{songBook ? songBook.name : "Unbekannt"}
</td>
<td className="p-3 text-center font-mono text-blue-600 dark:text-blue-400 font-bold">
{song.song_number}
@@ -137,9 +135,9 @@ function Songs({ actionName = "Auswählen", onSelectSong, className = "", ...pro
</table>
</div>
</Card>
);
)
}
export const Screens = {
Songs: Songs,
};
}
+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>;
+15 -8
View File
@@ -1,7 +1,14 @@
import { prisma } from "@/lib/db/prisma";
import { parseInt } from "@/lib/helper/checkvar";
import type * as API from "./response";
// For Error checking use this import: import { Prisma } from "@prisma/client";
interface Response {
success: boolean;
status: number;
songs?: [];
error?: string;
}
/**
* GetSongs
@@ -9,7 +16,7 @@ import { parseInt } from "@/lib/helper/checkvar";
*
* @returns {"success": boolean, "status": number, "songs": [{"id":number, "title": string},...]}
*/
export async function getSongs() {
export async function getSongs(): Promise<API.GetSongsResponse> {
try{
const songs = await prisma.song.findMany({
select: {
@@ -35,7 +42,7 @@ export async function getSongs() {
* @param id - ID indicatin the song
* @returns {"success": boolean, "status": number, "song": {"id":number, "title": string, "songBooks": [{"songNumber": number, "book": {"title": string, "language": string}},...]}}
*/
export async function getSongById(rawId: number) {
export async function getSongById(rawId: number): Promise<API.GetSongDetailedResponse> {
try{
const id = parseInt(rawId);
if (!id) {
@@ -78,13 +85,13 @@ export async function getSongById(rawId: number) {
*
* @param query - The search term for the song title.
* @param limit - Max number of songs returned for performance (default: 20).
* @returns @returns {"success": boolean, "status": number, "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 searchSongsByTitle(query: string, limit: number = 20) {
export async function searchSongsByTitle(query: string, limit: number = 20): Promise<API.GetSongsDelailedResponse> {
try {
const cleanQuery = query.trim();
if (!cleanQuery) {
return { success: true, songBooks: [] };
return { success: true, status: 200, songs: [] };
}
const songs = await prisma.song.findMany({
@@ -124,7 +131,7 @@ export async function searchSongsByTitle(query: string, limit: number = 20) {
* @param data - object with title
* @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{
if(!data.title){
return { success: false, status: 400, error: "Field 'title' is required" };
@@ -164,7 +171,7 @@ export async function createSong(data: { title: string }) {
export async function updateSong(
rawId: number,
data: { title?: string }
) {
): Promise<API.CreateSongsResponse> {
try {
const id = parseInt(rawId);
if (!id) {
@@ -213,7 +220,7 @@ export async function updateSong(
* @param id - ID indicatin the song
* @returns {"success": boolean, "status": number, "song": {"id": number, "title": string}}
*/
export async function deleteSong(rawId: number) {
export async function deleteSong(rawId: number): Promise<API.CreateSongsResponse> {
try {
const id = parseInt(rawId);
if (!id) {
+1 -1
View File
@@ -1,6 +1,6 @@
export function parseInt(rawInteger){
export function parseInt(rawInteger: number){
const integer = Number.parseInt(rawInteger);
if (Number.isNaN(integer) || !Number.isInteger(integer)) {
+1 -5
View File
@@ -6,11 +6,7 @@
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "eslint",
"postinstall": "prisma generate",
"predev": "prisma migrate deploy",
"prestart": "prisma migrate deploy",
"db:setup": "node -e \"require('fs').existsSync('.env')||require('fs').copyFileSync('example.env','.env')\" && prisma migrate deploy && prisma generate"
"lint": "eslint"
},
"dependencies": {
"@prisma/adapter-better-sqlite3": "^7.9.1",