forked from redis/node-redis
-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.ts
114 lines (98 loc) · 2.82 KB
/
index.ts
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
import * as CONFIG_GET from './CONFIG_GET';
import * as CONFIG_SET from './CONFIG_SET';;
import * as DELETE from './DELETE';
import * as EXPLAIN from './EXPLAIN';
import * as LIST from './LIST';
import * as PROFILE from './PROFILE';
import * as QUERY from './QUERY';
import * as RO_QUERY from './RO_QUERY';
import * as SLOWLOG from './SLOWLOG';
import { RedisCommandArgument, RedisCommandArguments } from '@redis/client/dist/lib/commands';
export default {
CONFIG_GET,
configGet: CONFIG_GET,
CONFIG_SET,
configSet: CONFIG_SET,
DELETE,
delete: DELETE,
EXPLAIN,
explain: EXPLAIN,
LIST,
list: LIST,
PROFILE,
profile: PROFILE,
QUERY,
query: QUERY,
RO_QUERY,
roQuery: RO_QUERY,
SLOWLOG,
slowLog: SLOWLOG
};
type QueryParam = null | string | number | boolean | QueryParams | Array<QueryParam>;
type QueryParams = {
[key: string]: QueryParam;
};
export interface QueryOptions {
params?: QueryParams;
TIMEOUT?: number;
}
export type QueryOptionsBackwardCompatible = QueryOptions | number;
export function pushQueryArguments(
args: RedisCommandArguments,
graph: RedisCommandArgument,
query: RedisCommandArgument,
options?: QueryOptionsBackwardCompatible,
compact?: boolean
): RedisCommandArguments {
args.push(graph);
if (typeof options === 'number') {
args.push(query);
pushTimeout(args, options);
} else {
args.push(
options?.params ?
`CYPHER ${queryParamsToString(options.params)} ${query}` :
query
);
if (options?.TIMEOUT !== undefined) {
pushTimeout(args, options.TIMEOUT);
}
}
if (compact) {
args.push('--compact');
}
return args;
}
function pushTimeout(args: RedisCommandArguments, timeout: number): void {
args.push('TIMEOUT', timeout.toString());
}
function queryParamsToString(params: QueryParams): string {
const parts = [];
for (const [key, value] of Object.entries(params)) {
parts.push(`${key}=${queryParamToString(value)}`);
}
return parts.join(' ');
}
function queryParamToString(param: QueryParam): string {
if (param === null) {
return 'null';
}
switch (typeof param) {
case 'string':
return `"${param.replace(/["\\]/g, '\\$&')}"`;
case 'number':
case 'boolean':
return param.toString();
}
if (Array.isArray(param)) {
return `[${param.map(queryParamToString).join(',')}]`;
} else if (typeof param === 'object') {
const body = [];
for (const [key, value] of Object.entries(param)) {
body.push(`${key}:${queryParamToString(value)}`);
}
return `{${body.join(',')}}`;
} else {
throw new TypeError(`Unexpected param type ${typeof param} ${param}`)
}
}