History: Add history service and usage

Add history service to allow for CRUD operations.
Use history service in controllers to:
  1. Allow manipulating of history entries
  2. Guaranty the correct existence of history entries

Signed-off-by: Philip Molares <philip.molares@udo.edu>
This commit is contained in:
Philip Molares 2021-02-03 21:22:55 +01:00
parent b76fa91a3c
commit 7f1afc30c9
8 changed files with 173 additions and 118 deletions

View file

@ -17,15 +17,16 @@ import {
Request, Request,
} from '@nestjs/common'; } from '@nestjs/common';
import { HistoryEntryUpdateDto } from '../../../history/history-entry-update.dto'; import { HistoryEntryUpdateDto } from '../../../history/history-entry-update.dto';
import { HistoryEntryDto } from '../../../history/history-entry.dto';
import { HistoryService } from '../../../history/history.service'; import { HistoryService } from '../../../history/history.service';
import { ConsoleLoggerService } from '../../../logger/console-logger.service'; import { ConsoleLoggerService } from '../../../logger/console-logger.service';
import { NoteMetadataDto } from '../../../notes/note-metadata.dto'; import { NoteMetadataDto } from '../../../notes/note-metadata.dto';
import { NotesService } from '../../../notes/notes.service'; import { NotesService } from '../../../notes/notes.service';
import { UserInfoDto } from '../../../users/user-info.dto';
import { UsersService } from '../../../users/users.service'; import { UsersService } from '../../../users/users.service';
import { TokenAuthGuard } from '../../../auth/token-auth.guard'; import { TokenAuthGuard } from '../../../auth/token-auth.guard';
import { ApiSecurity } from '@nestjs/swagger'; import { ApiSecurity } from '@nestjs/swagger';
import { HistoryEntryDto } from '../../../history/history-entry.dto';
import { UserInfoDto } from '../../../users/user-info.dto';
import { NotInDBError } from '../../../errors/errors';
@ApiSecurity('token') @ApiSecurity('token')
@Controller('me') @Controller('me')
@ -49,19 +50,37 @@ export class MeController {
@UseGuards(TokenAuthGuard) @UseGuards(TokenAuthGuard)
@Get('history') @Get('history')
getUserHistory(@Request() req): HistoryEntryDto[] { async getUserHistory(@Request() req): Promise<HistoryEntryDto[]> {
return this.historyService.getUserHistory(req.user.userName); const foundEntries = await this.historyService.getEntriesByUser(req.user);
return Promise.all(
foundEntries.map(
async (entry) => await this.historyService.toHistoryEntryDto(entry),
),
);
} }
@UseGuards(TokenAuthGuard) @UseGuards(TokenAuthGuard)
@Put('history/:note') @Put('history/:note')
updateHistoryEntry( async updateHistoryEntry(
@Request() req, @Request() req,
@Param('note') note: string, @Param('note') note: string,
@Body() entryUpdateDto: HistoryEntryUpdateDto, @Body() entryUpdateDto: HistoryEntryUpdateDto,
): HistoryEntryDto { ): Promise<HistoryEntryDto> {
// ToDo: Check if user is allowed to pin this history entry // ToDo: Check if user is allowed to pin this history entry
return this.historyService.updateHistoryEntry(note, entryUpdateDto); try {
return this.historyService.toHistoryEntryDto(
await this.historyService.updateHistoryEntry(
note,
req.user,
entryUpdateDto,
),
);
} catch (e) {
if (e instanceof NotInDBError) {
throw new NotFoundException(e.message);
}
throw e;
}
} }
@UseGuards(TokenAuthGuard) @UseGuards(TokenAuthGuard)
@ -70,9 +89,12 @@ export class MeController {
deleteHistoryEntry(@Request() req, @Param('note') note: string) { deleteHistoryEntry(@Request() req, @Param('note') note: string) {
// ToDo: Check if user is allowed to delete note // ToDo: Check if user is allowed to delete note
try { try {
return this.historyService.deleteHistoryEntry(note); return this.historyService.deleteHistoryEntry(note, req.user);
} catch (e) { } catch (e) {
throw new NotFoundException(e.message); if (e instanceof NotInDBError) {
throw new NotFoundException(e.message);
}
throw e;
} }
} }

View file

@ -28,6 +28,7 @@ import { RevisionsService } from '../../../revisions/revisions.service';
import { MarkdownBody } from '../../utils/markdownbody-decorator'; import { MarkdownBody } from '../../utils/markdownbody-decorator';
import { TokenAuthGuard } from '../../../auth/token-auth.guard'; import { TokenAuthGuard } from '../../../auth/token-auth.guard';
import { ApiSecurity } from '@nestjs/swagger'; import { ApiSecurity } from '@nestjs/swagger';
import { HistoryService } from '../../../history/history.service';
import { NoteDto } from '../../../notes/note.dto'; import { NoteDto } from '../../../notes/note.dto';
import { NoteMetadataDto } from '../../../notes/note-metadata.dto'; import { NoteMetadataDto } from '../../../notes/note-metadata.dto';
import { RevisionMetadataDto } from '../../../revisions/revision-metadata.dto'; import { RevisionMetadataDto } from '../../../revisions/revision-metadata.dto';
@ -40,6 +41,7 @@ export class NotesController {
private readonly logger: ConsoleLoggerService, private readonly logger: ConsoleLoggerService,
private noteService: NotesService, private noteService: NotesService,
private revisionsService: RevisionsService, private revisionsService: RevisionsService,
private historyService: HistoryService,
) { ) {
this.logger.setContext(NotesController.name); this.logger.setContext(NotesController.name);
} }
@ -57,6 +59,22 @@ export class NotesController {
); );
} }
@UseGuards(TokenAuthGuard)
@Get(':noteIdOrAlias')
async getNote(@Request() req, @Param('noteIdOrAlias') noteIdOrAlias: string) {
// ToDo: check if user is allowed to view this note
try {
const note = await this.noteService.getNoteByIdOrAlias(noteIdOrAlias);
await this.historyService.createOrUpdateHistoryEntry(note, req.user);
return this.noteService.toNoteDto(note);
} catch (e) {
if (e instanceof NotInDBError) {
throw new NotFoundException(e.message);
}
throw e;
}
}
@UseGuards(TokenAuthGuard) @UseGuards(TokenAuthGuard)
@Post(':noteAlias') @Post(':noteAlias')
async createNamedNote( async createNamedNote(
@ -71,25 +89,6 @@ export class NotesController {
); );
} }
@UseGuards(TokenAuthGuard)
@Get(':noteIdOrAlias')
async getNote(
@Request() req,
@Param('noteIdOrAlias') noteIdOrAlias: string,
): Promise<NoteDto> {
// ToDo: check if user is allowed to view this note
try {
return this.noteService.toNoteDto(
await this.noteService.getNoteByIdOrAlias(noteIdOrAlias),
);
} catch (e) {
if (e instanceof NotInDBError) {
throw new NotFoundException(e.message);
}
throw e;
}
}
@UseGuards(TokenAuthGuard) @UseGuards(TokenAuthGuard)
@Delete(':noteIdOrAlias') @Delete(':noteIdOrAlias')
async deleteNote( async deleteNote(

View file

@ -4,15 +4,33 @@
* SPDX-License-Identifier: AGPL-3.0-only * SPDX-License-Identifier: AGPL-3.0-only
*/ */
import { IsBoolean, ValidateNested } from 'class-validator'; import { IsArray, IsBoolean, IsDate, IsString } from 'class-validator';
import { NoteMetadataDto } from '../notes/note-metadata.dto';
export class HistoryEntryDto { export class HistoryEntryDto {
/** /**
* Metadata of this note * ID or Alias of the note
*/ */
@ValidateNested() @IsString()
metadata: NoteMetadataDto; identifier: string;
/**
* Title of the note
* Does not contain any markup but might be empty
* @example "Shopping List"
*/
@IsString()
title: string;
/**
* Datestring of the last time this note was updated
* @example "2020-12-01 12:23:34"
*/
@IsDate()
lastVisited: Date;
@IsArray()
@IsString({ each: true })
tags: string[];
/** /**
* True if this note is pinned * True if this note is pinned

View file

@ -4,12 +4,7 @@
* SPDX-License-Identifier: AGPL-3.0-only * SPDX-License-Identifier: AGPL-3.0-only
*/ */
import { import { Column, Entity, ManyToOne, UpdateDateColumn } from 'typeorm';
Column,
Entity,
ManyToOne,
UpdateDateColumn,
} from 'typeorm';
import { User } from '../users/user.entity'; import { User } from '../users/user.entity';
import { Note } from '../notes/note.entity'; import { Note } from '../notes/note.entity';

View file

@ -7,10 +7,19 @@
import { Module } from '@nestjs/common'; import { Module } from '@nestjs/common';
import { LoggerModule } from '../logger/logger.module'; import { LoggerModule } from '../logger/logger.module';
import { HistoryService } from './history.service'; import { HistoryService } from './history.service';
import { TypeOrmModule } from '@nestjs/typeorm';
import { HistoryEntry } from './history-entry.entity';
import { UsersModule } from '../users/users.module';
import { NotesModule } from '../notes/notes.module';
@Module({ @Module({
providers: [HistoryService], providers: [HistoryService],
exports: [HistoryService], exports: [HistoryService],
imports: [LoggerModule], imports: [
LoggerModule,
TypeOrmModule.forFeature([HistoryEntry]),
UsersModule,
NotesModule,
],
}) })
export class HistoryModule {} export class HistoryModule {}

View file

@ -8,90 +8,98 @@ import { Injectable } from '@nestjs/common';
import { ConsoleLoggerService } from '../logger/console-logger.service'; import { ConsoleLoggerService } from '../logger/console-logger.service';
import { HistoryEntryUpdateDto } from './history-entry-update.dto'; import { HistoryEntryUpdateDto } from './history-entry-update.dto';
import { HistoryEntryDto } from './history-entry.dto'; import { HistoryEntryDto } from './history-entry.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { HistoryEntry } from './history-entry.enity';
import { UsersService } from '../users/users.service';
import { NotesService } from '../notes/notes.service';
import { User } from '../users/user.entity';
import { Note } from '../notes/note.entity';
import { NotInDBError } from '../errors/errors';
@Injectable() @Injectable()
export class HistoryService { export class HistoryService {
constructor(private readonly logger: ConsoleLoggerService) { constructor(
private readonly logger: ConsoleLoggerService,
@InjectRepository(HistoryEntry)
private historyEntryRepository: Repository<HistoryEntry>,
private usersService: UsersService,
private notesService: NotesService,
) {
this.logger.setContext(HistoryService.name); this.logger.setContext(HistoryService.name);
} }
getUserHistory(username: string): HistoryEntryDto[] { async getEntriesByUser(user: User): Promise<HistoryEntry[]> {
//TODO: Use the database return await this.historyEntryRepository.find({
this.logger.warn('Using hardcoded data!'); where: { user: user },
return [ relations: ['note'],
{ });
metadata: {
alias: null,
createTime: new Date(),
description: 'Very descriptive text.',
editedBy: [],
id: 'foobar-barfoo',
permissions: {
owner: {
displayName: 'foo',
userName: 'fooUser',
email: 'foo@example.com',
photo: '',
},
sharedToUsers: [],
sharedToGroups: [],
},
tags: [],
title: 'Title!',
updateTime: new Date(),
updateUser: {
displayName: 'foo',
userName: 'fooUser',
email: 'foo@example.com',
photo: '',
},
viewCount: 42,
},
pinStatus: false,
},
];
} }
updateHistoryEntry( private async getEntryByNoteIdOrAlias(
noteId: string, noteIdOrAlias: string,
updateDto: HistoryEntryUpdateDto, user: User,
): HistoryEntryDto { ): Promise<HistoryEntry> {
//TODO: Use the database const note = await this.notesService.getNoteByIdOrAlias(noteIdOrAlias);
this.logger.warn('Using hardcoded data!'); return await this.getEntryByNote(note, user);
return { }
metadata: {
alias: null, private async getEntryByNote(note: Note, user: User): Promise<HistoryEntry> {
createTime: new Date(), return await this.historyEntryRepository.findOne({
description: 'Very descriptive text.', where: {
editedBy: [], note: note,
id: 'foobar-barfoo', user: user,
permissions: {
owner: {
displayName: 'foo',
userName: 'fooUser',
email: 'foo@example.com',
photo: '',
},
sharedToUsers: [],
sharedToGroups: [],
},
tags: [],
title: 'Title!',
updateTime: new Date(),
updateUser: {
displayName: 'foo',
userName: 'fooUser',
email: 'foo@example.com',
photo: '',
},
viewCount: 42,
}, },
pinStatus: updateDto.pinStatus, relations: ['note', 'user'],
});
}
async createOrUpdateHistoryEntry(
note: Note,
user: User,
): Promise<HistoryEntry> {
let entry = await this.getEntryByNote(note, user);
if (!entry) {
entry = HistoryEntry.create(user, note);
} else {
entry.updatedAt = new Date();
}
return await this.historyEntryRepository.save(entry);
}
async updateHistoryEntry(
noteIdOrAlias: string,
user: User,
updateDto: HistoryEntryUpdateDto,
): Promise<HistoryEntry> {
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 this.historyEntryRepository.save(entry);
}
async deleteHistoryEntry(noteIdOrAlias: string, user: User): Promise<void> {
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;
}
async toHistoryEntryDto(entry: HistoryEntry): Promise<HistoryEntryDto> {
return {
identifier: entry.note.alias ? entry.note.alias : entry.note.id,
lastVisited: entry.updatedAt,
tags: this.notesService.toTagList(entry.note),
title: entry.note.title,
pinStatus: entry.pinStatus,
}; };
} }
deleteHistoryEntry(note: string) {
//TODO: Use the database and actually do stuff
throw new Error('Not implemented');
}
} }

View file

@ -177,6 +177,10 @@ export class NotesService {
return this.getCurrentContent(note); return this.getCurrentContent(note);
} }
toTagList(note: Note): string[] {
return note.tags.map((tag) => tag.name);
}
async toNotePermissionsDto(note: Note): Promise<NotePermissionsDto> { async toNotePermissionsDto(note: Note): Promise<NotePermissionsDto> {
return { return {
owner: this.usersService.toUserDto(note.owner), owner: this.usersService.toUserDto(note.owner),
@ -204,7 +208,7 @@ export class NotesService {
), ),
// TODO: Extract into method // TODO: Extract into method
permissions: await this.toNotePermissionsDto(note), permissions: await this.toNotePermissionsDto(note),
tags: note.tags.map((tag) => tag.name), tags: this.toTagList(note),
updateTime: (await this.getLatestRevision(note)).createdAt, updateTime: (await this.getLatestRevision(note)).createdAt,
// TODO: Get actual updateUser // TODO: Get actual updateUser
updateUser: { updateUser: {

View file

@ -85,7 +85,7 @@ describe('Notes', () => {
.delete('/me/history/test3') .delete('/me/history/test3')
.expect(204); .expect(204);
expect(response.body.content).toBeNull(); expect(response.body.content).toBeNull();
const history = historyService.getUserHistory('testuser'); const history = historyService.getEntriesByUser('testuser');
let historyEntry: HistoryEntryDto = null; let historyEntry: HistoryEntryDto = null;
for (const e of history) { for (const e of history) {
if (e.metadata.alias === noteName) { if (e.metadata.alias === noteName) {
@ -106,7 +106,7 @@ describe('Notes', () => {
.send(historyEntryUpdateDto) .send(historyEntryUpdateDto)
.expect(200); .expect(200);
// TODO parameter is not used for now // TODO parameter is not used for now
const history = historyService.getUserHistory('testuser'); const history = historyService.getEntriesByUser('testuser');
let historyEntry: HistoryEntryDto; let historyEntry: HistoryEntryDto;
for (const e of <any[]>response.body.content) { for (const e of <any[]>response.body.content) {
if ((<HistoryEntryDto>e).metadata.alias === noteName) { if ((<HistoryEntryDto>e).metadata.alias === noteName) {