65 lines
1.7 KiB
TypeScript
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 };
|
|
}
|
|
}
|