Skip to content

Commit 5465fed

Browse files
authored
Merge pull request #1 from PlatziDev/hotfix/cache-key
It solve in get cache key problem when body json has different order in N requests
2 parents 50233e3 + 3c3b972 commit 5465fed

File tree

2 files changed

+32
-4
lines changed

2 files changed

+32
-4
lines changed

src/cache.test.ts

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,11 +12,11 @@ describe('cache', () => {
1212
method: 'POST',
1313
path: '/v1/completions',
1414
authHeader: 'api-key-!',
15-
body: '{ "ok": true }',
15+
body: '{"ok":true}',
1616
};
1717
const result = await getCacheKey(params);
1818
expect(utils.objectHash).toHaveBeenCalledWith(params);
19-
expect(result).toEqual('1a97143b720b3d82cf93a34a5a02c61de1492b18d813f4f1859251eef1a738be');
19+
expect(result).toEqual('de8cb85a7a697a5ee1458b31857c4db1c94760b2a14681052170bed55bf6db1b');
2020
});
2121

2222
it('removes null or empty values', async () => {
@@ -33,5 +33,25 @@ describe('cache', () => {
3333
});
3434
expect(result).toEqual('771798e93f4fbad36b4c89cd88d3752383224caf8e585661dc174feb25939f75');
3535
});
36+
37+
it('returns a same hash uniquely representing the params when body has different order', async () => {
38+
let params = {
39+
method: 'POST',
40+
path: '/v1/completions',
41+
authHeader: null,
42+
body: '{"key1":"1","key2":"2"}',
43+
};
44+
let result = await getCacheKey(params);
45+
expect(result).toEqual('91b1af0c3f20778905ab588460bcb1d14b4621445f32fd871d7fe23056142923');
46+
47+
params = {
48+
method: 'POST',
49+
path: '/v1/completions',
50+
authHeader: null,
51+
body: '{"key2":"2","key1":"1"}',
52+
};
53+
result = await getCacheKey(params);
54+
expect(result).toEqual('91b1af0c3f20778905ab588460bcb1d14b4621445f32fd871d7fe23056142923');
55+
});
3656
});
3757
});

src/cache.ts

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,16 @@ export const getCacheKey = async (props: GetCacheKeyProps): Promise<string> => {
1212
// https://stackoverflow.com/a/40924449
1313
const propsWithoutUndefined = Object.keys(props).reduce((acc, key) => {
1414
const _acc: Record<string, any> = acc;
15-
const propValue = (props as any)[key];
16-
if (propValue != null && propValue !== '') {
15+
let propValue = (props as any)[key];
16+
if (key === 'body' && propValue !== '') {
17+
try {
18+
const body = JSON.parse(propValue);
19+
propValue = JSON.stringify(body, Object.keys(body).sort());
20+
} catch (_error) {
21+
propValue = '';
22+
}
23+
}
24+
if (propValue !== null && propValue !== '') {
1725
_acc[key] = propValue;
1826
}
1927
return _acc;

0 commit comments

Comments
 (0)