From 8357f3072cb91794b63fa24b74745282d9898d5c Mon Sep 17 00:00:00 2001 From: David Mehren Date: Thu, 29 Apr 2021 16:16:30 +0200 Subject: [PATCH] HistoryService: Throw NotInDBError on empty DB result This adds error handling to getEntryByNote, so it throws a NotInDBError instead of (illegally, according to the type) returning null. Signed-off-by: David Mehren --- src/history/history.service.ts | 32 ++++++++++++++++---------------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/src/history/history.service.ts b/src/history/history.service.ts index fa4aed431..fd733f732 100644 --- a/src/history/history.service.ts +++ b/src/history/history.service.ts @@ -69,13 +69,19 @@ export class HistoryService { * @return {HistoryEntry} the requested history entry */ private async getEntryByNote(note: Note, user: User): Promise { - return await this.historyEntryRepository.findOne({ + const entry = await this.historyEntryRepository.findOne({ where: { note: note, user: user, }, relations: ['note', 'user'], }); + if (!entry) { + throw new NotInDBError( + `User '${user.userName}' has no HistoryEntry for Note with id '${note.id}'`, + ); + } + return entry; } /** @@ -89,13 +95,17 @@ export class HistoryService { note: Note, user: User, ): Promise { - let entry = await this.getEntryByNote(note, user); - if (!entry) { - entry = HistoryEntry.create(user, note); - } else { + try { + const entry = await this.getEntryByNote(note, user); entry.updatedAt = new Date(); + return await this.historyEntryRepository.save(entry); + } catch (e) { + if (e instanceof NotInDBError) { + const entry = HistoryEntry.create(user, note); + return await this.historyEntryRepository.save(entry); + } + throw e; } - return await this.historyEntryRepository.save(entry); } /** @@ -112,11 +122,6 @@ export class HistoryService { updateDto: HistoryEntryUpdateDto, ): Promise { const entry = await this.getEntryByNoteIdOrAlias(noteIdOrAlias, user); - if (!entry) { - throw new NotInDBError( - `User '${user.userName}' has no HistoryEntry for Note with id '${noteIdOrAlias}'`, - ); - } entry.pinStatus = updateDto.pinStatus; return await this.historyEntryRepository.save(entry); } @@ -130,11 +135,6 @@ export class HistoryService { */ async deleteHistoryEntry(noteIdOrAlias: string, user: User): Promise { const entry = await this.getEntryByNoteIdOrAlias(noteIdOrAlias, user); - if (!entry) { - throw new NotInDBError( - `User '${user.userName}' has no HistoryEntry for Note with id '${noteIdOrAlias}'`, - ); - } await this.historyEntryRepository.remove(entry); return; }