0

I have NestJs api for e-books service Please help me for one question. How can I delete file and update database entity in one transaction, for prevent case when file was been deleted, but database entity update had error?

public async deleteBookFile(id: number, file: string) {
        try {
            const paths = (await this.bookRepository.findOne({ where: { id } }))
                .path as unknown as string[]
            if (paths) {
                unlink(`${__dirname}/files/book/${file}`, async (error) => {
                    if (error) {
                        throw new InternalServerErrorException("Delete service error!")
                    } else {
                        await this.bookRepository.update(
                            id, 
                            { path: paths.filter(path => path !== file) as unknown as string })
                        return { status: "deleted" }
                    }
                })
            }
            throw new BadRequestException("Delete file service error: Paths can't been resolved")
        } catch (error) {
            
        }
    }

Also if you can, explain me more easier way for update path property, in my case it has string and simple-array type

0 Answers0