import { ConflictException, Injectable, NotFoundException, } from "@nestjs/common"; import { InjectRepository } from "@nestjs/typeorm"; import { Repository } from "typeorm"; import { PaginatedResult, PaginationQueryDto, } from "../common/dto/pagination.dto"; import { CreateEnvironmentDto } from "./dto/create-environment.dto"; import { EnvironmentExportDto } from "./dto/environment-export.dto"; import { UpdateEnvironmentDto } from "./dto/update-environment.dto"; import { EnvironmentEntity } from "./environment.entity"; export type EnvironmentOrderBy = "id" | "name" | "createdAt" | "updatedAt"; @Injectable() export class EnvironmentService { constructor( @InjectRepository(EnvironmentEntity) private readonly repo: Repository, ) {} async create(dto: CreateEnvironmentDto): Promise { const existing = await this.repo.findOneBy({ name: dto.name }); if (existing) { throw new ConflictException(`Environment "${dto.name}" already exists`); } return this.repo.save(this.repo.create(dto)); } async findAll( query: PaginationQueryDto = {}, ): Promise> { const page = query.page ?? 1; const limit = query.limit ?? 20; const orderBy = query.orderBy ?? "id"; const orderDir = query.orderDir ?? "ASC"; const [data, total] = await this.repo.findAndCount({ order: { [orderBy]: orderDir }, skip: (page - 1) * limit, take: limit, }); return { data, total, page, limit }; } async findOne(id: string): Promise { const env = await this.repo.findOneBy({ id }); if (!env) throw new NotFoundException(`Environment ${id} not found`); return env; } async update( id: string, dto: UpdateEnvironmentDto, ): Promise { const env = await this.findOne(id); Object.assign(env, dto); return this.repo.save(env); } async remove(id: string): Promise { await this.findOne(id); await this.repo.delete(id); } exportEnvironment(env: EnvironmentEntity): EnvironmentExportDto { return { kind: "environment", id: env.id, name: env.name, description: env.description ?? undefined, data: env.data, }; } async importEnvironment( dto: EnvironmentExportDto, ): Promise { if (dto.id) { const existing = await this.repo.findOneBy({ id: dto.id }); if (existing) { Object.assign(existing, { name: dto.name, description: dto.description ?? null, data: dto.data, }); return this.repo.save(existing); } return this.repo.save( this.repo.create({ id: dto.id, name: dto.name, description: dto.description ?? null, data: dto.data, }), ); } const byName = await this.repo.findOneBy({ name: dto.name }); if (byName) { Object.assign(byName, { description: dto.description ?? null, data: dto.data, }); return this.repo.save(byName); } return this.repo.save( this.repo.create({ name: dto.name, description: dto.description ?? null, data: dto.data, }), ); } }