Skip to content

Commit

Permalink
feat(http): Create memory cache provider (#33900)
Browse files Browse the repository at this point in the history
  • Loading branch information
zharinov authored Feb 10, 2025
1 parent b5ae2f5 commit 1e702c2
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 0 deletions.
39 changes: 39 additions & 0 deletions lib/util/http/cache/memory-http-cache-provider.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import { Http } from '..';
import * as httpMock from '../../../../test/http-mock';
import * as memCache from '../../cache/memory';
import { memCacheProvider as cacheProvider } from './memory-http-cache-provider';

describe('util/http/cache/memory-http-cache-provider', () => {
beforeEach(() => {
memCache.init();
});

afterEach(() => {
memCache.reset();
});

const http = new Http('test');

it('reuses data with etag', async () => {
const scope = httpMock.scope('https://example.com');

scope.get('/foo/bar').reply(200, { msg: 'Hello, world!' }, { etag: '123' });
const res1 = await http.getJsonUnchecked('https://example.com/foo/bar', {
cacheProvider,
});
expect(res1).toMatchObject({
statusCode: 200,
body: { msg: 'Hello, world!' },
authorization: false,
});

const res2 = await http.getJsonUnchecked('https://example.com/foo/bar', {
cacheProvider,
});
expect(res2).toMatchObject({
statusCode: 200,
body: { msg: 'Hello, world!' },
authorization: false,
});
});
});
21 changes: 21 additions & 0 deletions lib/util/http/cache/memory-http-cache-provider.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import * as memCache from '../../cache/memory';
import { AbstractHttpCacheProvider } from './abstract-http-cache-provider';
import type { HttpCache } from './schema';

export class MemoryHttpCacheProvider extends AbstractHttpCacheProvider {
private cacheKey(url: string): string {
return `memory-cache-http-provider:${url}`;
}

protected override load(url: string): Promise<unknown> {
const data = memCache.get<HttpCache>(this.cacheKey(url));
return Promise.resolve(data);
}

protected override persist(url: string, data: HttpCache): Promise<void> {
memCache.set(this.cacheKey(url), data);
return Promise.resolve();
}
}

export const memCacheProvider = new MemoryHttpCacheProvider();

0 comments on commit 1e702c2

Please sign in to comment.