-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathErc20RepositoryCache.ts
More file actions
47 lines (40 loc) · 1.3 KB
/
Erc20RepositoryCache.ts
File metadata and controls
47 lines (40 loc) · 1.3 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
import { injectable } from 'inversify';
import { Erc20, Erc20Repository } from './Erc20Repository';
import { CacheRepository } from '../CacheRepository/CacheRepository';
import { SupportedChainId } from '@cowprotocol/cow-sdk';
import { getCacheKey, PartialCacheKey } from '../../utils/cache';
const NULL_VALUE = 'null';
@injectable()
export class Erc20RepositoryCache implements Erc20Repository {
private baseCacheKey: PartialCacheKey[];
constructor(
private proxy: Erc20Repository,
private cache: CacheRepository,
cacheName: string,
private cacheTimeSeconds: number
) {
this.baseCacheKey = ['repos', cacheName];
}
async get(
chainId: SupportedChainId,
tokenAddress: string
): Promise<Erc20 | null> {
// Get cached value
const cacheKey = getCacheKey(
...this.baseCacheKey,
'get',
chainId,
tokenAddress
);
const valueString = await this.cache.get(cacheKey);
if (valueString) {
return valueString === NULL_VALUE ? null : JSON.parse(valueString);
}
// Get fresh value from proxy
const value = await this.proxy.get(chainId, tokenAddress);
// Cache value
const cacheValue = value === null ? NULL_VALUE : JSON.stringify(value);
await this.cache.set(cacheKey, cacheValue, this.cacheTimeSeconds);
return value;
}
}