UsersService: Add methods to find, create and delete users

Signed-off-by: David Mehren <git@herrmehren.de>
This commit is contained in:
David Mehren 2020-10-12 21:46:53 +02:00
parent ec8cf6d33e
commit 7997a0955a
No known key found for this signature in database
GPG key ID: 185982BA4C42B7C3
3 changed files with 49 additions and 13 deletions

View file

@ -29,8 +29,10 @@ export class MeController {
}
@Get()
getMe(): UserInfoDto {
return this.usersService.getUserInfo();
async getMe(): Promise<UserInfoDto> {
return this.usersService.toUserDto(
await this.usersService.getUserByUsername('hardcoded'),
);
}
@Get('history')

View file

@ -48,4 +48,20 @@ export class User {
identity => identity.user,
)
identities: Identity[];
// eslint-disable-next-line @typescript-eslint/no-empty-function
private constructor() {}
public static create(
userName: string,
displayName: string,
): Pick<
User,
'userName' | 'displayName' | 'ownedNotes' | 'authToken' | 'identities'
> {
const newUser = new User();
newUser.userName = userName;
newUser.displayName = displayName;
return newUser;
}
}

View file

@ -1,26 +1,44 @@
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { NotInDBError } from '../errors/errors';
import { ConsoleLoggerService } from '../logger/console-logger.service';
import { UserInfoDto } from './user-info.dto';
import { User } from './user.entity';
@Injectable()
export class UsersService {
constructor(private readonly logger: ConsoleLoggerService) {
constructor(
private readonly logger: ConsoleLoggerService,
@InjectRepository(User) private userRepository: Repository<User>,
) {
this.logger.setContext(UsersService.name);
}
getUserInfo(): UserInfoDto {
//TODO: Use the database
this.logger.warn('Using hardcoded data!');
return {
displayName: 'foo',
userName: 'fooUser',
email: 'foo@example.com',
photo: '',
};
createUser(userName: string, displayName: string): Promise<User> {
const user = User.create(userName, displayName);
return this.userRepository.save(user);
}
getPhotoUrl(user: User) {
async deleteUser(userName: string) {
//TOOD: Handle owned notes and edits
const user = await this.userRepository.findOne({
where: { userName: userName },
});
await this.userRepository.delete(user);
}
async getUserByUsername(userName: string): Promise<User> {
const user = this.userRepository.findOne({
where: { userName: userName },
});
if (user === undefined) {
throw new NotInDBError(`User with username '${userName}' not found`);
}
return user;
}
getPhotoUrl(user: User): string {
if (user.photo) {
return user.photo;
} else {