refactor: adapt for typeorm 0.3

Signed-off-by: David Mehren <git@herrmehren.de>
This commit is contained in:
David Mehren 2022-04-17 22:00:04 +02:00
parent 43d3f14322
commit 06c39ea759
5 changed files with 89 additions and 76 deletions

View file

@ -5,8 +5,8 @@
*/ */
import { ConfigModule } from '@nestjs/config'; import { ConfigModule } from '@nestjs/config';
import { Test, TestingModule } from '@nestjs/testing'; import { Test, TestingModule } from '@nestjs/testing';
import { getConnectionToken, getRepositoryToken } from '@nestjs/typeorm'; import { getDataSourceToken, getRepositoryToken } from '@nestjs/typeorm';
import { Connection, Repository } from 'typeorm'; import { DataSource, Repository } from 'typeorm';
import { AuthToken } from '../auth/auth-token.entity'; import { AuthToken } from '../auth/auth-token.entity';
import { Author } from '../authors/author.entity'; import { Author } from '../authors/author.entity';
@ -34,7 +34,7 @@ import { HistoryService } from './history.service';
describe('HistoryService', () => { describe('HistoryService', () => {
let service: HistoryService; let service: HistoryService;
let historyRepo: Repository<HistoryEntry>; let historyRepo: Repository<HistoryEntry>;
let connection; let dataSource: DataSource;
let noteRepo: Repository<Note>; let noteRepo: Repository<Note>;
type MockConnection = { type MockConnection = {
@ -52,7 +52,7 @@ describe('HistoryService', () => {
providers: [ providers: [
HistoryService, HistoryService,
{ {
provide: getConnectionToken(), provide: getDataSourceToken(),
useFactory: mockConnection, useFactory: mockConnection,
}, },
{ {
@ -106,7 +106,7 @@ describe('HistoryService', () => {
historyRepo = module.get<Repository<HistoryEntry>>( historyRepo = module.get<Repository<HistoryEntry>>(
getRepositoryToken(HistoryEntry), getRepositoryToken(HistoryEntry),
); );
connection = module.get<Connection>(Connection); dataSource = module.get<DataSource>(DataSource);
noteRepo = module.get<Repository<Note>>(getRepositoryToken(Note)); noteRepo = module.get<Repository<Note>>(getRepositoryToken(Note));
}); });
@ -467,8 +467,10 @@ describe('HistoryService', () => {
expect(entry.updatedAt).toEqual(newlyCreatedHistoryEntry.updatedAt); expect(entry.updatedAt).toEqual(newlyCreatedHistoryEntry.updatedAt);
}), }),
}; };
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
// eslint-disable-next-line @typescript-eslint/no-unsafe-call // eslint-disable-next-line @typescript-eslint/no-unsafe-call
connection.transaction.mockImplementation((cb) => { dataSource.transaction.mockImplementation((cb) => {
// eslint-disable-next-line @typescript-eslint/no-unsafe-call // eslint-disable-next-line @typescript-eslint/no-unsafe-call
cb(mockedManager); cb(mockedManager);
}); });

View file

@ -59,6 +59,7 @@ export class HistoryService {
.where('entry.note = :note', { note: note.id }) .where('entry.note = :note', { note: note.id })
.andWhere('entry.user = :user', { user: user.id }) .andWhere('entry.user = :user', { user: user.id })
.leftJoinAndSelect('entry.note', 'note') .leftJoinAndSelect('entry.note', 'note')
.leftJoinAndSelect('entry.user', 'user')
.getOne(); .getOne();
if (!entry) { if (!entry) {
throw new NotInDBError( throw new NotInDBError(

View file

@ -49,7 +49,7 @@ export class IdentityService {
}, },
relations: ['user'], relations: ['user'],
}); });
if (identity === undefined) { if (identity === null) {
throw new NotInDBError(`Identity for user id '${userId}' not found`); throw new NotInDBError(`Identity for user id '${userId}' not found`);
} }
return identity; return identity;

View file

@ -91,14 +91,18 @@ describe('NotesService', () => {
note.owner = Promise.resolve(user); note.owner = Promise.resolve(user);
note.userPermissions = Promise.resolve([ note.userPermissions = Promise.resolve([
{ {
noteId: note.id,
note: note, note: note,
userId: user.id,
user: user, user: user,
canEdit: true, canEdit: true,
}, },
]); ]);
note.groupPermissions = Promise.resolve([ note.groupPermissions = Promise.resolve([
{ {
noteId: note.id,
note: note, note: note,
groupId: group.id,
group: group, group: group,
canEdit: true, canEdit: true,
}, },

View file

@ -51,79 +51,85 @@ const dataSource = new DataSource({
dropSchema: true, dropSchema: true,
}); });
dataSource.initialize().then(async () => { dataSource
const password = 'test_password'; .initialize()
const users = []; .then(async () => {
users.push(User.create('hardcoded', 'Test User 1')); const password = 'test_password';
users.push(User.create('hardcoded_2', 'Test User 2')); const users = [];
users.push(User.create('hardcoded_3', 'Test User 3')); users.push(User.create('hardcoded', 'Test User 1'));
const notes: Note[] = []; users.push(User.create('hardcoded_2', 'Test User 2'));
notes.push(Note.create(null, 'test') as Note); users.push(User.create('hardcoded_3', 'Test User 3'));
notes.push(Note.create(null, 'test2') as Note); const notes: Note[] = [];
notes.push(Note.create(null, 'test3') as Note); notes.push(Note.create(null, 'test') as Note);
notes.push(Note.create(null, 'test2') as Note);
notes.push(Note.create(null, 'test3') as Note);
for (let i = 0; i < 3; i++) { for (let i = 0; i < 3; i++) {
const author = await dataSource.manager.save(dataSource.manager.create(Author, Author.create(1))) as Author; const author = (await dataSource.manager.save(
const user = await dataSource.manager.save(dataSource.manager.create(User, users[i])) as User; dataSource.manager.create(Author, Author.create(1)),
const identity = Identity.create(user, ProviderType.LOCAL, false); )) as Author;
identity.passwordHash = await hashPassword(password); const user = (await dataSource.manager.save(
dataSource.manager.create(Identity, identity); dataSource.manager.create(User, users[i]),
author.user = (dataSource.manager.save(user) as Promise<User>); )) as User;
const revision = Revision.create( const identity = Identity.create(user, ProviderType.LOCAL, false);
'This is a test note', identity.passwordHash = await hashPassword(password);
'This is a test note', dataSource.manager.create(Identity, identity);
notes[i], author.user = dataSource.manager.save(user);
) as Revision; const revision = Revision.create(
const edit = Edit.create(author, 1, 42) as Edit; 'This is a test note',
revision.edits = Promise.resolve([edit]); 'This is a test note',
notes[i].revisions = Promise.all([revision]); notes[i],
notes[i].userPermissions = Promise.resolve([]); ) as Revision;
notes[i].groupPermissions = Promise.resolve([]); const edit = Edit.create(author, 1, 42) as Edit;
user.ownedNotes = Promise.resolve([notes[i]]); revision.edits = Promise.resolve([edit]);
await dataSource.manager.save([ notes[i].revisions = Promise.all([revision]);
notes[i], notes[i].userPermissions = Promise.resolve([]);
user, notes[i].groupPermissions = Promise.resolve([]);
revision, user.ownedNotes = Promise.resolve([notes[i]]);
edit, await dataSource.manager.save([
author, notes[i],
identity, user,
]); revision,
} edit,
const foundUsers = await dataSource.manager.find(User); author,
if (!foundUsers) { identity,
throw new Error('Could not find freshly seeded users. Aborting.'); ]);
} }
const foundNotes = await dataSource.manager.find(Note, { const foundUsers = await dataSource.manager.find(User);
relations: ['aliases'], if (!foundUsers) {
}); throw new Error('Could not find freshly seeded users. Aborting.');
if (!foundNotes) { }
throw new Error('Could not find freshly seeded notes. Aborting.'); const foundNotes = await dataSource.manager.find(Note, {
} relations: ['aliases'],
for (const note of foundNotes) { });
if (!(await note.aliases)[0]) { if (!foundNotes) {
throw new Error( throw new Error('Could not find freshly seeded notes. Aborting.');
'Could not find alias of freshly seeded notes. Aborting.',
);
} }
}
for (const user of foundUsers) {
console.log(
`Created User '${user.username}' with password '${password}'`,
);
}
for (const note of foundNotes) {
console.log(`Created Note '${(await note.aliases)[0].name ?? ''}'`);
}
for (const user of foundUsers) {
for (const note of foundNotes) { for (const note of foundNotes) {
const historyEntry = HistoryEntry.create(user, note); if (!(await note.aliases)[0]) {
await dataSource.manager.save(historyEntry); throw new Error(
'Could not find alias of freshly seeded notes. Aborting.',
);
}
}
for (const user of foundUsers) {
console.log( console.log(
`Created HistoryEntry for user '${user.username}' and note '${ `Created User '${user.username}' with password '${password}'`,
(await note.aliases)[0].name ?? ''
}'`,
); );
} }
} for (const note of foundNotes) {
}) console.log(`Created Note '${(await note.aliases)[0].name ?? ''}'`);
}
for (const user of foundUsers) {
for (const note of foundNotes) {
const historyEntry = HistoryEntry.create(user, note);
await dataSource.manager.save(historyEntry);
console.log(
`Created HistoryEntry for user '${user.username}' and note '${
(await note.aliases)[0].name ?? ''
}'`,
);
}
}
})
.catch((error) => console.log(error)); .catch((error) => console.log(error));