/
redis-view-set.ts
75 lines (69 loc) · 2.08 KB
/
redis-view-set.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
import { ViewSet, ViewSetQuery } from 'nest-rest-framework';
import {
RedisRepository,
EntityPrimaryKeyPropertyName,
EntityPrimaryKeyValueModifier,
NewEntityConstructor,
} from './redis-repository';
import { Logger, NotFoundException, BadRequestException } from '@nestjs/common';
export abstract class RedisViewSet<DataT> extends ViewSet<string, DataT> {
private readonly logger: Logger;
constructor(
protected readonly redisRepository: RedisRepository,
protected readonly entityConstructor: NewEntityConstructor<DataT>,
protected readonly primaryKeyPropertyName: EntityPrimaryKeyPropertyName<
DataT
>,
protected readonly primaryKeyValuePrefix: EntityPrimaryKeyValueModifier<
DataT
>,
) {
super();
this.logger = new Logger(RedisViewSet.name);
}
async query(query?: ViewSetQuery): Promise<DataT[]> {
const message = 'Redis does not allow Queries. It is a key-value store!!';
this.logger.error(message);
throw new BadRequestException(message);
}
async create(data: DataT): Promise<DataT> {
await this.redisRepository.save(
[data],
this.primaryKeyPropertyName,
this.primaryKeyValuePrefix,
);
return data;
}
async retrieve(pk: string): Promise<DataT> {
const response = await this.redisRepository.get(
[pk],
this.entityConstructor,
this.primaryKeyValuePrefix,
);
if (!!response && response.length > 0) {
return response[0];
}
throw new NotFoundException(
`Unable to find key ${pk} for type ${this.primaryKeyValuePrefix}`,
);
}
async replace(pk: string, data: DataT): Promise<DataT> {
await this.redisRepository.save(
[data],
this.primaryKeyPropertyName,
this.primaryKeyValuePrefix,
);
return data;
}
async modify(pk: string, data: DataT): Promise<DataT> {
await this.redisRepository.save(
[data],
this.primaryKeyPropertyName,
this.primaryKeyValuePrefix,
);
return data;
}
async destroy(pk: string): Promise<void> {
await this.redisRepository.delete([pk], this.primaryKeyValuePrefix);
}
}