add file upload service

This commit is contained in:
andres
2023-07-16 13:55:05 +02:00
parent df1f041961
commit cde1d9fd02
8 changed files with 547 additions and 17 deletions

View File

@@ -2,18 +2,24 @@ import { CommandHandler, ICommandHandler } from '@nestjs/cqrs'
import { CardsRepository } from '../infrastructure/cards.repository'
import { UpdateCardDto } from '../dto/update-card.dto'
import { BadRequestException, NotFoundException } from '@nestjs/common'
import { FileUploadService } from '../../../infrastructure/file-upload-service/file-upload.service'
export class UpdateCardCommand {
constructor(
public readonly cardId: string,
public readonly card: UpdateCardDto,
public readonly userId: string
public readonly userId: string,
public readonly answerImg?: Express.Multer.File,
public readonly questionImg?: Express.Multer.File
) {}
}
@CommandHandler(UpdateCardCommand)
export class UpdateCardHandler implements ICommandHandler<UpdateCardCommand> {
constructor(private readonly cardsRepository: CardsRepository) {}
constructor(
private readonly cardsRepository: CardsRepository,
private readonly fileUploadService: FileUploadService
) {}
async execute(command: UpdateCardCommand) {
const card = await this.cardsRepository.findCardById(command.cardId)
@@ -24,6 +30,32 @@ export class UpdateCardHandler implements ICommandHandler<UpdateCardCommand> {
throw new BadRequestException(`You can't change a card that you don't own`)
}
return await this.cardsRepository.updateCardById(command.cardId, command.card)
const addQuestionImagePromise = this.fileUploadService.uploadFile(
command.questionImg.buffer,
command.questionImg.originalname
)
const addAnswerImagePromise = this.fileUploadService.uploadFile(
command.answerImg.buffer,
command.answerImg.originalname
)
let questionImg, answerImg
if (command.questionImg && command.answerImg) {
const result = await Promise.all([addQuestionImagePromise, addAnswerImagePromise])
questionImg = result[0].fileUrl
answerImg = result[1].fileUrl
} else if (command.answerImg) {
const result = await addAnswerImagePromise
answerImg = result.fileUrl
} else if (command.questionImg) {
const result = await addQuestionImagePromise
questionImg = result.fileUrl
}
return await this.cardsRepository.updateCardById(command.cardId, {
...command.card,
answerImg,
questionImg,
})
}
}