-
Notifications
You must be signed in to change notification settings - Fork 913
Expand file tree
/
Copy pathUserService.ts
More file actions
60 lines (50 loc) · 2.04 KB
/
UserService.ts
File metadata and controls
60 lines (50 loc) · 2.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import { Service } from 'typedi';
import { OrmRepository } from 'typeorm-typedi-extensions';
import uuid from 'uuid';
import { EventDispatcher, EventDispatcherInterface } from '../../decorators/EventDispatcher';
import { Logger, LoggerInterface } from '../../decorators/Logger';
import { User } from '../models/User';
import { UserRepository } from '../repositories/UserRepository';
import { events } from '../subscribers/events';
@Service()
export class UserService {
constructor(
@OrmRepository() private userRepository: UserRepository,
@EventDispatcher() private eventDispatcher: EventDispatcherInterface,
@Logger(__filename) private log: LoggerInterface
) { }
public find(): Promise<User[]> {
this.log.info('Find all users');
return this.userRepository.find({ relations: ['pets'] });
}
public findOne(id: string): Promise<User | undefined> {
this.log.info('Find one user');
return this.userRepository.findOne({ id });
}
public async create(user: User): Promise<User> {
this.log.info('Create a new user => ', user.toString());
user.id = uuid.v1();
const newUser = await this.userRepository.save(user);
this.eventDispatcher.dispatch(events.user.created, newUser);
return newUser;
}
public update(id: string, user: User): Promise<User> {
this.log.info('Update a user');
user.id = id;
return this.userRepository.save(user);
}
public async delete(id: string): Promise<void> {
this.log.info('Delete a user');
await this.userRepository.delete(id);
return;
}
public search(query: string): Promise<User[]> {
this.log.info('Search users with pattern');
const lowerQuery = query.toLowerCase();
return this.userRepository
.createQueryBuilder('user')
.where('LOWER(user.firstName) LIKE :query', { query: `%${lowerQuery}%` })
.orWhere('LOWER(user.lastName) LIKE :query', { query: `%${lowerQuery}%` })
.getMany();
}
}