/
helper.ts
119 lines (105 loc) · 2.34 KB
/
helper.ts
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
import { bind } from 'decko';
import { Router } from 'express';
import { Repository, FindManyOptions, FindOneOptions } from 'typeorm';
import { AuthService } from '../../services/auth';
import { RedisService } from '../../services/redis';
export interface IComponentRoutes<T> {
readonly name: string;
readonly controller: T;
readonly router: Router;
authSerivce: AuthService;
initRoutes(): void;
initChildRoutes?(): void;
}
export abstract class AbsRepository<T> {
protected readonly name: string;
protected readonly repo: Repository<T>;
protected readonly defaultRelations: string[];
constructor(name: string, repo: Repository<T>, defaultRelations: string[] = []) {
this.name = name;
this.repo = repo;
this.defaultRelations = defaultRelations;
}
/**
* Delete cache entries
*/
@bind
deleteFromCache() {
RedisService.deleteByKey(this.name);
}
/**
* Read all entities from db
*
* @param options Find options
* @param cached Use cache
* @returns Entity array
*/
@bind
readAll(options: FindManyOptions<T> = {}, cached?: boolean): Promise<T[]> {
try {
if (Object.keys(options).length) {
return this.repo.find({
relations: this.defaultRelations,
...options
});
}
if (cached) {
return RedisService.getAndSetObject<T[]>(this.name, () => this.readAll({}, false));
}
return this.repo.find({
relations: this.defaultRelations
});
} catch (err) {
throw new Error(err);
}
}
/**
* Read a certain entity from db
*
* @param options Find options
* @returns Entity
*/
@bind
read(options: FindOneOptions<T>): Promise<T | undefined> {
try {
return this.repo.findOne({
relations: this.defaultRelations,
...options
});
} catch (err) {
throw new Error(err);
}
}
/**
* Save new or updated entity to db
*
* @param entity Entity to save
* @returns Saved entity
*/
@bind
async save(entity: T): Promise<T> {
try {
const saved: T = await this.repo.save(entity);
this.deleteFromCache();
return saved;
} catch (err) {
throw new Error(err);
}
}
/**
* Delete entity from db
*
* @param entity Entity to delete
* @returns Deleted entity
*/
@bind
async delete(entity: T): Promise<T> {
try {
const deleted = await this.repo.remove(entity);
this.deleteFromCache();
return deleted;
} catch (err) {
throw new Error(err);
}
}
}