Skip to content

Commit b56ec4b

Browse files
authored
feat(cache): Add Memory Caching In Format Versions Endpoint (#559)
add memory caching in format versions endpoint
1 parent 185dadb commit b56ec4b

File tree

2 files changed

+26
-2
lines changed

2 files changed

+26
-2
lines changed

src/server/controller/formatVersion.ts

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,12 @@ export default class FormatVersionController {
99

1010
public async list(_req: Request, res: Response): Promise<void> {
1111
const formatVersionEntity = await this.repository.list();
12-
res.status(200).setHeader('Content-Type', 'application/json').send(formatVersionEntity);
12+
res
13+
.status(200)
14+
.setHeader('Content-Type', 'application/json')
15+
.setHeader('Cache-Control', 'public, max-age=3600') // Cache for 1 hour
16+
.setHeader('ETag', `"${formatVersionEntity.join(',')}"`) // Simple ETag based on content
17+
.send(formatVersionEntity);
1318
}
1419

1520
public async listPruefisByFormatVersion(req: Request, res: Response): Promise<void> {

src/server/repository/formatVersion.ts

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,9 @@ interface PruefiWithName {
2020
export default class FormatVersionRepository extends BlobStorageContainerBacked {
2121
private ahbContainerName: string;
2222
private formatVersionContainerName: string;
23+
private formatVersionsCache: { versions: string[]; timestamp: number } | null = null;
24+
private readonly CACHE_TTL = 3600000; // 1 hour in milliseconds
25+
2326
constructor(client?: BlobServiceClient) {
2427
super(client);
2528
if (!process.env['AHB_CONTAINER_NAME']) {
@@ -35,6 +38,14 @@ export default class FormatVersionRepository extends BlobStorageContainerBacked
3538

3639
// Return a list of all unique format versions from the database
3740
public async list(): Promise<string[]> {
41+
// Check if we have a valid cache
42+
if (
43+
this.formatVersionsCache &&
44+
Date.now() - this.formatVersionsCache.timestamp < this.CACHE_TTL
45+
) {
46+
return this.formatVersionsCache.versions;
47+
}
48+
3849
// Initialize the database connection if not already initialized
3950
if (!AppDataSource.isInitialized) {
4051
await AppDataSource.initialize();
@@ -46,7 +57,15 @@ export default class FormatVersionRepository extends BlobStorageContainerBacked
4657
.orderBy('ahb.format_version')
4758
.getRawMany();
4859

49-
return formatVersions.map(result => result.formatVersion);
60+
const versions = formatVersions.map(result => result.formatVersion);
61+
62+
// Update cache
63+
this.formatVersionsCache = {
64+
versions,
65+
timestamp: Date.now(),
66+
};
67+
68+
return versions;
5069
}
5170

5271
// Return a list of all pruefis for a specific format version by looking at the json files

0 commit comments

Comments
 (0)