refactor(revision): lazy-load relations

Signed-off-by: David Mehren <git@herrmehren.de>
This commit is contained in:
David Mehren 2021-12-05 21:38:36 +01:00
parent 4e70044a2c
commit 5f87406809
No known key found for this signature in database
GPG key ID: 185982BA4C42B7C3
3 changed files with 11 additions and 10 deletions

View file

@ -711,7 +711,7 @@ describe('NotesService', () => {
.mockImplementation(async (note: Note): Promise<Note> => note);
const note = await service.createNote(content, null);
const revisions = await note.revisions;
revisions[0].edits = [
revisions[0].edits = Promise.resolve([
{
revisions: Promise.resolve(revisions),
startPos: 0,
@ -726,7 +726,7 @@ describe('NotesService', () => {
updatedAt: new Date(1549312452001),
author: Promise.resolve(author),
} as Edit,
];
]);
revisions[0].createdAt = new Date(1549312452000);
jest.spyOn(revisionRepo, 'findOne').mockResolvedValue(revisions[0]);
const createQueryBuilder = {
@ -810,7 +810,7 @@ describe('NotesService', () => {
.mockImplementation(async (note: Note): Promise<Note> => note);
const note = await service.createNote(content, null);
const revisions = await note.revisions;
revisions[0].edits = [
revisions[0].edits = Promise.resolve([
{
revisions: Promise.resolve(revisions),
startPos: 0,
@ -825,7 +825,7 @@ describe('NotesService', () => {
updatedAt: new Date(1549312452001),
author: Promise.resolve(author),
} as Edit,
];
]);
revisions[0].createdAt = new Date(1549312452000);
jest
.spyOn(revisionRepo, 'findOne')

View file

@ -340,11 +340,12 @@ export class NotesService {
*/
async calculateUpdateUser(note: Note): Promise<User | null> {
const lastRevision = await this.getLatestRevision(note);
if (lastRevision && lastRevision.edits) {
const edits = await lastRevision.edits;
if (edits.length > 0) {
// Sort the last Revisions Edits by their updatedAt Date to get the latest one
// the user of that Edit is the updateUser
return await (
await lastRevision.edits.sort(
await edits.sort(
(a, b) => b.updatedAt.getTime() - a.updatedAt.getTime(),
)[0].author
).user;

View file

@ -58,14 +58,14 @@ export class Revision {
* Note this revision belongs to.
*/
@ManyToOne((_) => Note, (note) => note.revisions, { onDelete: 'CASCADE' })
note: Note;
note: Promise<Note>;
/**
* All edit objects which are used in the revision.
*/
@ManyToMany((_) => Edit, (edit) => edit.revisions)
@JoinTable()
edits: Edit[];
edits: Promise<Edit[]>;
// eslint-disable-next-line @typescript-eslint/no-empty-function
private constructor() {}
@ -79,8 +79,8 @@ export class Revision {
newRevision.patch = patch;
newRevision.content = content;
newRevision.length = content.length;
newRevision.note = note;
newRevision.edits = [];
newRevision.note = Promise.resolve(note);
newRevision.edits = Promise.resolve([]);
return newRevision;
}
}