-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathcommand.ts
117 lines (101 loc) · 2.31 KB
/
command.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
115
116
117
type SupportCommands = 'set' | 'get' | 'add' | 'replace';
export interface IMemCommand {
/**
* The name of the support command.
*
* @type {SupportCommands}
*/
name: SupportCommands;
/**
* The key corresponding to the command.
*
* @type {string}
*/
key: string;
/**
* Flags for the command.
* This is used in set, add and replace command.
*
* @type {?number}
*/
flags?: number;
/**
* The expiry time in seconds for the data.
* This is used in set, add and replace command.
*
* @type {?number}
*/
expTime?: number;
/**
* Number of bytes for the data.
* This is used in set, add and replace command.
*
* @type {?number}
*/
byteCount?: number;
/**
* If true then the server will not reply to the command.
*
* @type {?boolean}
*/
noReply?: boolean;
}
export class MemCommand implements IMemCommand {
name;
key;
flags?;
expTime?;
byteCount?;
noReply?;
constructor(
commandName: SupportCommands,
key: string,
flags?: number,
expTime?: number,
byteCount?: number,
noReply: boolean = false
) {
this.name = commandName;
this.key = key;
this.flags = flags;
this.expTime = expTime;
this.byteCount = byteCount;
this.noReply = noReply;
}
}
/**
* Function used to parse a valid command.
* The commands follow the following format:
*
* `<command name> <key> <flags> <expTime> <byte count> [noreply]`
*
* The trailing CRLF is already removed while reading the data from the socket.
*
* @export
* @param {string} input
* @returns {IMemCommand}
*/
export function parseMemCommand(input: string): IMemCommand {
// Split the command params with space
const params = input.split(' ');
const name = params[0] as SupportCommands;
const key = params[1];
let flags;
if (params[2]) {
flags = parseInt(params[2]);
}
let expTime;
if (params[3] && (name === 'set' || name === 'add' || name === 'replace')) {
try {
expTime = parseInt(params[3]);
} catch (e) {
expTime = undefined;
}
}
let byteCount;
if (params[4] && (name === 'set' || name === 'add' || name === 'replace')) {
byteCount = parseInt(params[4]);
}
const noreply = params[params.length - 1] === 'noreply';
return new MemCommand(name, key, flags, expTime, byteCount, noreply);
}