refactor: make permission service less complex

Signed-off-by: Tilman Vatteroth <git@tilmanvatteroth.de>
This commit is contained in:
Tilman Vatteroth 2023-03-26 18:12:23 +02:00
parent 0f8effd318
commit 8fc59aad82

View file

@ -236,14 +236,12 @@ export class PermissionsService {
canEdit: boolean, canEdit: boolean,
): Promise<Note> { ): Promise<Note> {
const permissions = await note.userPermissions; const permissions = await note.userPermissions;
let permissionIndex = 0; const permission = await this.findPermissionForUser(
const permission = permissions.find(async (value, index) => { permissions,
permissionIndex = index; permissionUser,
return (await value.user).id == permissionUser.id; );
}); if (permission !== undefined) {
if (permission != undefined) {
permission.canEdit = canEdit; permission.canEdit = canEdit;
permissions[permissionIndex] = permission;
} else { } else {
const noteUserPermission = NoteUserPermission.create( const noteUserPermission = NoteUserPermission.create(
permissionUser, permissionUser,
@ -256,6 +254,18 @@ export class PermissionsService {
return await this.noteRepository.save(note); return await this.noteRepository.save(note);
} }
private async findPermissionForUser(
permissions: NoteUserPermission[],
user: User,
): Promise<NoteUserPermission | undefined> {
for (const permission of permissions) {
if ((await permission.user).id == user.id) {
return permission;
}
}
return undefined;
}
/** /**
* @async * @async
* Remove permission for a specific user on a note. * Remove permission for a specific user on a note.
@ -294,14 +304,12 @@ export class PermissionsService {
'setGroupPermission', 'setGroupPermission',
); );
const permissions = await note.groupPermissions; const permissions = await note.groupPermissions;
let permissionIndex = 0; const permission = await this.findPermissionForGroup(
const permission = permissions.find(async (value, index) => { permissions,
permissionIndex = index; permissionGroup,
return (await value.group).id == permissionGroup.id; );
}); if (permission !== undefined) {
if (permission != undefined) {
permission.canEdit = canEdit; permission.canEdit = canEdit;
permissions[permissionIndex] = permission;
} else { } else {
this.logger.debug( this.logger.debug(
`Permission does not exist yet, creating new one.`, `Permission does not exist yet, creating new one.`,
@ -318,6 +326,18 @@ export class PermissionsService {
return await this.noteRepository.save(note); return await this.noteRepository.save(note);
} }
private async findPermissionForGroup(
permissions: NoteGroupPermission[],
group: Group,
): Promise<NoteGroupPermission | undefined> {
for (const permission of permissions) {
if ((await permission.group).id == group.id) {
return permission;
}
}
return undefined;
}
/** /**
* @async * @async
* Remove permission for a specific group on a note. * Remove permission for a specific group on a note.