@@ -2,12 +2,39 @@ import { Redis } from '@upstash/redis/cloudflare';
2
2
import { Env } from './env' ;
3
3
import { getHeadersAsObject , objectHash } from './utils' ;
4
4
5
+ interface AnyObject {
6
+ [ key : string ] : any ;
7
+ }
8
+
9
+ function sortObjectKeys ( obj : AnyObject ) : AnyObject {
10
+ const sortedKeys = Object . keys ( obj ) . sort ( ) ;
11
+ const sortedObj : AnyObject = { } ;
12
+
13
+ sortedKeys . forEach ( ( key ) => {
14
+ if ( typeof obj [ key ] === 'object' && ! Array . isArray ( obj [ key ] ) ) {
15
+ sortedObj [ key ] = sortObjectKeys ( obj [ key ] ) ;
16
+ } else if ( Array . isArray ( obj [ key ] ) ) {
17
+ sortedObj [ key ] = obj [ key ] . map ( ( item : any ) => {
18
+ if ( typeof item === 'object' && ! Array . isArray ( item ) ) {
19
+ return sortObjectKeys ( item ) ;
20
+ }
21
+ return item ;
22
+ } ) ;
23
+ } else {
24
+ sortedObj [ key ] = obj [ key ] ;
25
+ }
26
+ } ) ;
27
+
28
+ return sortedObj ;
29
+ }
30
+
5
31
interface GetCacheKeyProps {
6
32
method : string ;
7
33
path : string ;
8
34
authHeader : string | null ;
9
35
body : string | null ;
10
36
}
37
+
11
38
export const getCacheKey = async ( props : GetCacheKeyProps ) : Promise < string > => {
12
39
// https://stackoverflow.com/a/40924449
13
40
const propsWithoutUndefined = Object . keys ( props ) . reduce ( ( acc , key ) => {
@@ -16,7 +43,23 @@ export const getCacheKey = async (props: GetCacheKeyProps): Promise<string> => {
16
43
if ( key === 'body' && propValue !== '' ) {
17
44
try {
18
45
const body = JSON . parse ( propValue ) ;
19
- propValue = JSON . stringify ( body , Object . keys ( body ) . sort ( ) ) ;
46
+ const sortedBody : AnyObject = { } ;
47
+ const sortedKeys = Object . keys ( body ) . sort ( ) ;
48
+ sortedKeys . forEach ( ( key ) => {
49
+ if ( typeof body [ key ] === 'object' && ! Array . isArray ( body [ key ] ) ) {
50
+ sortedBody [ key ] = sortObjectKeys ( body [ key ] ) ;
51
+ } else if ( Array . isArray ( body [ key ] ) ) {
52
+ sortedBody [ key ] = body [ key ] . map ( ( item : any ) => {
53
+ if ( typeof item === 'object' && ! Array . isArray ( item ) ) {
54
+ return sortObjectKeys ( item ) ;
55
+ }
56
+ return item ;
57
+ } ) ;
58
+ } else {
59
+ sortedBody [ key ] = body [ key ] ;
60
+ }
61
+ } ) ;
62
+ propValue = JSON . stringify ( sortedBody ) ;
20
63
} catch ( _error ) {
21
64
propValue = '' ;
22
65
}
0 commit comments