canina/backend/src/admin/media.service.ts
parsa aghaei 62bd8811fa
All checks were successful
Deploy Canina / deploy (push) Successful in 4m58s
style: apply standard ESLint & Prettier formatting across backend
2026-07-29 15:41:53 +03:30

65 lines
1.7 KiB
TypeScript

import { Injectable, BadRequestException } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
import * as path from 'path';
import * as fs from 'fs';
@Injectable()
export class MediaService {
constructor(private prisma: PrismaService) {}
async getAllMedia() {
return this.prisma.media.findMany({
orderBy: { createdAt: 'desc' },
});
}
async uploadFile(file: Express.Multer.File) {
if (!file) {
throw new BadRequestException('No file uploaded');
}
const uploadDir = path.join(process.cwd(), 'uploads');
if (!fs.existsSync(uploadDir)) {
fs.mkdirSync(uploadDir, { recursive: true });
}
const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1e9);
const ext = path.extname(file.originalname);
const filename = `${uniqueSuffix}${ext}`;
const filePath = path.join(uploadDir, filename);
fs.writeFileSync(filePath, file.buffer);
// Assuming we serve static files from '/uploads' route prefix
const url = `/uploads/${filename}`;
const media = await this.prisma.media.create({
data: {
filename: file.originalname,
url,
mimetype: file.mimetype,
size: file.size,
},
});
return media;
}
async deleteMedia(id: string) {
const media = await this.prisma.media.findUnique({ where: { id } });
if (!media) throw new BadRequestException('Media not found');
const filePath = path.join(
process.cwd(),
'uploads',
path.basename(media.url),
);
if (fs.existsSync(filePath)) {
fs.unlinkSync(filePath);
}
await this.prisma.media.delete({ where: { id } });
return { success: true };
}
}