Files
ritzenbergen-backend/src/galerie/galerie.service.ts
T
2026-05-05 12:29:45 +02:00

61 lines
1.7 KiB
TypeScript

import { Injectable } from "@nestjs/common";
import { promises as fs } from 'fs';
import * as path from 'path';
import { JahrMitBild } from "src/dto/galerie.dto";
@Injectable()
export class GalerieService {
private readonly imagesPath = "/bilder";
constructor(
){}
async getBilder(
event: string,
jahr: number
): Promise<string[]> {
const files= await fs.readdir(path.join(this.imagesPath,event, jahr.toString()));
// Nur Bilddateien filtern
const imageFiles = files.filter(file =>
/\.(jpg|jpeg|png|gif|webp)$/i.test(file)
);
return imageFiles;
}
async getJahre(
event: string
): Promise<JahrMitBild[]> {
const files= await fs.readdir(path.join(this.imagesPath,event).toString());
// Nur Verzeichnisse filtern (Jahre)
const directories: JahrMitBild[] = [];
for (const file of files) {
const filePath = path.join(this.imagesPath, event, file);
const stat = await fs.stat(filePath);
if (stat.isDirectory()) {
directories.push(new JahrMitBild(parseInt(file), await this.getBilder(event,parseInt(file))));
}
}
return directories;
}
async getRandomImage(event: string, jahr: number): Promise<string>{
const bilder=await this.getBilder(event,jahr);
const index = Math.floor(Math.random() * bilder.length);
return bilder[index];
}
async getRandomYear(event:string): Promise<number>{
const jahre=(await this.getJahre(event)).map((jahr)=>jahr.jahr);
const index = Math.floor(Math.random() * jahre.length);
return jahre[index];
}
}