UsersService: Polish methods

Add test to createUser method to ensure an already used username triggers a AlreadyInDBError.
Add debug entry if user is deleted.
Add changeDisplayName method.

Signed-off-by: Philip Molares <philip.molares@udo.edu>
This commit is contained in:
Philip Molares 2021-03-05 00:30:03 +01:00 committed by David Mehren
parent bce0ca9d74
commit b86a7c601d
No known key found for this signature in database
GPG key ID: 185982BA4C42B7C3

View file

@ -31,21 +31,42 @@ export class UsersService {
*/ */
async createUser(userName: string, displayName: string): Promise<User> { async createUser(userName: string, displayName: string): Promise<User> {
const user = User.create(userName, displayName); const user = User.create(userName, displayName);
return this.userRepository.save(user); try {
return await this.userRepository.save(user);
} catch {
this.logger.debug(
`A user with the username '${userName}' already exists.`,
'createUser',
);
throw new AlreadyInDBError(
`A user with the username '${userName}' already exists.`,
);
}
} }
/** /**
* @async * @async
* Delete the user with the specified userName * Delete the user with the specified userName
* @param userName - the username of the user to be delete * @param {User} user - the username of the user to be delete
* @throws {NotInDBError} the userName has no user associated with it. * @throws {NotInDBError} the userName has no user associated with it.
*/ */
async deleteUser(userName: string): Promise<void> { async deleteUser(user: User): Promise<void> {
// TODO: Handle owned notes and edits await this.userRepository.remove(user);
const user = await this.userRepository.findOne({ this.logger.debug(
where: { userName: userName }, `Successfully deleted user with username ${user.userName}`,
}); 'deleteUser',
await this.userRepository.delete(user); );
}
/**
* @async
* Change the displayName of the specified user
* @param {User} user - the user to be changed
* @param displayName - the new displayName
*/
async changeDisplayName(user: User, displayName: string): Promise<void> {
user.displayName = displayName;
await this.userRepository.save(user);
} }
/** /**
@ -56,9 +77,13 @@ export class UsersService {
* @return {User} the specified user * @return {User} the specified user
*/ */
async getUserByUsername(userName: string, withTokens = false): Promise<User> { async getUserByUsername(userName: string, withTokens = false): Promise<User> {
const relations: string[] = [];
if (withTokens) {
relations.push('authTokens');
}
const user = await this.userRepository.findOne({ const user = await this.userRepository.findOne({
where: { userName: userName }, where: { userName: userName },
relations: withTokens ? ['authTokens'] : null, relations: relations,
}); });
if (user === undefined) { if (user === undefined) {
throw new NotInDBError(`User with username '${userName}' not found`); throw new NotInDBError(`User with username '${userName}' not found`);