import { CommandHandler, ICommandHandler } from '@nestjs/cqrs'; import { ProjectRole } from '@task-stream/api/tracker/domain'; import { AttachmentStorage, attachmentKey } from '../ports/attachment-storage'; import { CommandResult, ack } from './command-result'; import { DetachFileCommand } from './detach-file.command'; import { WriteAccess } from './write-access'; /** Removes the record first; the bytes go once nothing points at them. */ @CommandHandler(DetachFileCommand) export class DetachFileCommandHandler implements ICommandHandler { constructor( private readonly access: WriteAccess, private readonly storage: AttachmentStorage, ) {} async execute(command: DetachFileCommand): Promise { const { issue, project } = await this.access.issueForContributor( command.issueId, command.actorId, ); const role = project.roleOf(command.actorId); issue.detach( command.actorId, command.attachmentId, role === ProjectRole.OWNER || role === ProjectRole.ADMIN, ); await issue.commitAndWait(); await this.storage.remove( attachmentKey(issue.projectId, issue.id, command.attachmentId), ); return ack(issue); } }