Skip to content

Instantly share code, notes, and snippets.

@mgoria
Last active March 27, 2023 09:56
Show Gist options
  • Save mgoria/002de28a85f5257b1c9dfa68fbe338e4 to your computer and use it in GitHub Desktop.
Save mgoria/002de28a85f5257b1c9dfa68fbe338e4 to your computer and use it in GitHub Desktop.
async renameFolder (folderId: number, name: string): Promise<Folder> {
// this is an additional DB call in case we want to do app validation
// could be avioded if we run update opration directly
// in most cases it's impact is negligible (but depends on our overall usecase DB throughput)
const folder = await this.dbRepo.findOneBy({
id: folderId
})
// app layer validation - it's going to work in most of the cases
if (folder.name === name) {
throw new ConflictException('Folder with such name already exists')
}
folder.name = name
try {
// we still have to try catch this opperation since very rarelly but it might happen that the check above is not enough
// e.g. due to another rename operation being executed at the same time
await this.folderRepository.save(folder)
} catch (error) {
// here we try to cast all known / expected DB exectpions to app one
// e.g. unique constraints or other things
if (error instanceof TypeORMError && <is duplicate error>) {
throw new ConflictException('Folder with such name already exists')
}
logger.error('Failed to reaname folder', {
folderId,
name,
error
})
// in case the operation failed for an unknown reason we log the original error
// but cast the DB error to an app one and bubble it up
throw new InternalServerErrorException('Error renaming folder')
}
retrun folder
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment