61 lines
1.9 KiB
TypeScript
61 lines
1.9 KiB
TypeScript
import { Injectable, NotFoundException } from '@nestjs/common';
|
|
import { InjectRepository } from '@nestjs/typeorm';
|
|
import { Repository } from 'typeorm';
|
|
import { Project } from './project.entity';
|
|
|
|
@Injectable()
|
|
export class ProjectsService {
|
|
constructor(
|
|
@InjectRepository(Project)
|
|
private projectsRepository: Repository<Project>,
|
|
) {}
|
|
|
|
async create(data: { title: string; description?: string; ownerId: number }): Promise<Project> {
|
|
console.log('Received data:', data);
|
|
const project = this.projectsRepository.create({
|
|
title: data.title,
|
|
description: data.description,
|
|
ownerId: data.ownerId,
|
|
});
|
|
return this.projectsRepository.save(project);
|
|
}
|
|
|
|
|
|
async findAll(): Promise<Project[]> {
|
|
return this.projectsRepository.find();
|
|
}
|
|
|
|
async findByOwner(ownerId: number): Promise<Project[]> {
|
|
return this.projectsRepository.find({ where: { ownerId } });
|
|
}
|
|
|
|
async findOneById(id: number): Promise<Project | null> {
|
|
return this.projectsRepository.findOne({ where: { id } });
|
|
}
|
|
|
|
async update(id: number, data: { title?: string; description?: string }, ownerId: number): Promise<Project> {
|
|
const project = await this.findOneById(id);
|
|
if (!project) throw new NotFoundException('Project not found');
|
|
|
|
if (project.ownerId !== ownerId) {
|
|
throw new NotFoundException('You are not the owner of this project');
|
|
}
|
|
|
|
if (data.title !== undefined) project.title = data.title;
|
|
if (data.description !== undefined) project.description = data.description;
|
|
|
|
return this.projectsRepository.save(project);
|
|
}
|
|
|
|
async delete(id: number, ownerId: number): Promise<void> {
|
|
const project = await this.findOneById(id);
|
|
if (!project) throw new NotFoundException('Project not found');
|
|
|
|
if (project.ownerId !== ownerId) {
|
|
throw new NotFoundException('You are not the owner of this project');
|
|
}
|
|
|
|
await this.projectsRepository.delete(id);
|
|
}
|
|
}
|