import { Injectable, NotFoundException } from "@nestjs/common"; import { InjectRepository } from "@nestjs/typeorm"; import { Repository } from "typeorm"; import { CredentialEntity } from "./credential.entity"; import { CreateCredentialDto } from "./dto/create-credential.dto"; import { UpdateCredentialDto } from "./dto/update-credential.dto"; import { CredentialExportDto } from "./dto/credential-export.dto"; import { PaginationQueryDto, PaginatedResult, } from "../common/dto/pagination.dto"; export type CredentialOrderBy = "id" | "name" | "lastUsedAt" | "createdAt" | "updatedAt"; @Injectable() export class CredentialService { constructor( @InjectRepository(CredentialEntity) private readonly repo: Repository, ) {} async create(dto: CreateCredentialDto): Promise { return this.repo.save(this.repo.create({ ...dto, data: dto.data ?? null })); } 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 credential = await this.repo.findOneBy({ id }); if (!credential) throw new NotFoundException(`Credential ${id} not found`); return credential; } async update(id: string, dto: UpdateCredentialDto): Promise { const credential = await this.findOne(id); Object.assign(credential, dto); return this.repo.save(credential); } async remove(id: string): Promise { await this.findOne(id); await this.repo.delete(id); } exportCredential(credential: CredentialEntity): CredentialExportDto { return { kind: "credential", id: credential.id, name: credential.name, data: credential.data }; } async importCredential(dto: CredentialExportDto): Promise { if (dto.id) { const existing = await this.repo.findOneBy({ id: dto.id }); if (existing) { Object.assign(existing, { name: dto.name, data: dto.data ?? null }); return this.repo.save(existing); } return this.repo.save( this.repo.create({ id: dto.id, name: dto.name, data: dto.data ?? null }), ); } return this.repo.save( this.repo.create({ name: dto.name, data: dto.data ?? null }), ); } }