This repository has been archived by the owner on May 1, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 11
/
serialize.ts
559 lines (496 loc) · 14.9 KB
/
serialize.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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
/**
* Interprets an encoded string and returns either the string or null/undefined if not available.
* Ignores array inputs (takes just first element in array)
* @param input encoded string
*/
function getEncodedValue(
input: string | (string | null)[] | null | undefined,
allowEmptyString?: boolean
): string | null | undefined {
if (input == null) {
return input;
}
// '' or []
if (
input.length === 0 &&
(!allowEmptyString || (allowEmptyString && input !== ''))
) {
return null;
}
const str = input instanceof Array ? input[0] : input;
if (str == null) {
return str;
}
if (!allowEmptyString && str === '') {
return null;
}
return str;
}
/**
* Interprets an encoded string and return null/undefined or an array with
* the encoded string contents
* @param input encoded string
*/
function getEncodedValueArray(
input: string | (string | null)[] | null | undefined
): (string | null)[] | null | undefined {
if (input == null) {
return input;
}
return input instanceof Array ? input : input === '' ? [] : [input];
}
/**
* Encodes a date as a string in YYYY-MM-DD format.
*
* @param {Date} date
* @return {String} the encoded date
*/
export function encodeDate(
date: Date | null | undefined
): string | null | undefined {
if (date == null) {
return date;
}
const year = date.getFullYear();
const month = date.getMonth() + 1;
const day = date.getDate();
return `${year}-${month < 10 ? `0${month}` : month}-${
day < 10 ? `0${day}` : day
}`;
}
/**
* Converts a date in the format 'YYYY-mm-dd...' into a proper date, because
* new Date() does not do that correctly. The date can be as complete or incomplete
* as necessary (aka, '2015', '2015-10', '2015-10-01').
* It will not work for dates that have times included in them.
*
* If an array is provided, only the first entry is used.
*
* @param {String} input String date form like '2015-10-01'
* @return {Date} parsed date
*/
export function decodeDate(
input: string | (string | null)[] | null | undefined
): Date | null | undefined {
const dateString = getEncodedValue(input);
if (dateString == null) return dateString;
const parts = dateString.split('-') as any;
// may only be a year so won't even have a month
if (parts[1] != null) {
parts[1] -= 1; // Note: months are 0-based
} else {
// just a year, set the month and day to the first
parts[1] = 0;
parts[2] = 1;
}
const decoded = new Date(...(parts as [number, number, number]));
if (isNaN(decoded.getTime())) {
return null;
}
return decoded;
}
/**
* Encodes a date as a string in ISO 8601 ("2019-05-28T10:58:40Z") format.
*
* @param {Date} date
* @return {String} the encoded date
*/
export function encodeDateTime(
date: Date | null | undefined
): string | null | undefined {
if (date == null) {
return date;
}
return date.toISOString();
}
/**
* Converts a date in the https://en.wikipedia.org/wiki/ISO_8601 format.
* For allowed inputs see specs:
* - https://tools.ietf.org/html/rfc2822#page-14
* - http://www.ecma-international.org/ecma-262/5.1/#sec-15.9.1.15
*
* If an array is provided, only the first entry is used.
*
* @param {String} input String date form like '1995-12-17T03:24:00'
* @return {Date} parsed date
*/
export function decodeDateTime(
input: string | (string | null)[] | null | undefined
): Date | null | undefined {
const dateString = getEncodedValue(input);
if (dateString == null) return dateString;
const decoded = new Date(dateString);
if (isNaN(decoded.getTime())) {
return null;
}
return decoded;
}
/**
* Encodes a boolean as a string. true -> "1", false -> "0".
*
* @param {Boolean} bool
* @return {String} the encoded boolean
*/
export function encodeBoolean(
bool: boolean | null | undefined
): string | null | undefined {
if (bool == null) {
return bool;
}
return bool ? '1' : '0';
}
/**
* Decodes a boolean from a string. "1" -> true, "0" -> false.
* Everything else maps to undefined.
*
* If an array is provided, only the first entry is used.
*
* @param {String} input the encoded boolean string
* @return {Boolean} the boolean value
*/
export function decodeBoolean(
input: string | (string | null)[] | null | undefined
): boolean | null | undefined {
const boolStr = getEncodedValue(input);
if (boolStr == null) return boolStr;
if (boolStr === '1') {
return true;
} else if (boolStr === '0') {
return false;
}
return null;
}
/**
* Encodes a number as a string.
*
* @param {Number} num
* @return {String} the encoded number
*/
export function encodeNumber(
num: number | null | undefined
): string | null | undefined {
if (num == null) {
return num;
}
return String(num);
}
/**
* Decodes a number from a string. If the number is invalid,
* it returns undefined.
*
* If an array is provided, only the first entry is used.
*
* @param {String} input the encoded number string
* @return {Number} the number value
*/
export function decodeNumber(
input: string | (string | null)[] | null | undefined
): number | null | undefined {
const numStr = getEncodedValue(input);
if (numStr == null) return numStr;
if (numStr === '') return null;
const result = +numStr;
return result;
}
/**
* Encodes a string while safely handling null and undefined values.
*
* @param {String} str a string to encode
* @return {String} the encoded string
*/
export function encodeString(
str: string | (string | null)[] | null | undefined
): string | null | undefined {
if (str == null) {
return str;
}
return String(str);
}
/**
* Decodes a string while safely handling null and undefined values.
*
* If an array is provided, only the first entry is used.
*
* @param {String} input the encoded string
* @return {String} the string value
*/
export function decodeString(
input: string | (string | null)[] | null | undefined
): string | null | undefined {
const str = getEncodedValue(input, true);
if (str == null) return str;
return String(str);
}
/**
* Decodes an enum value while safely handling null and undefined values.
*
* If an array is provided, only the first entry is used.
*
* @param {String} input the encoded string
* @param {String[]} enumValues allowed enum values
* @return {String} the string value from enumValues
*/
export function decodeEnum<T extends string>(
input: string | (string | null)[] | null | undefined,
enumValues: T[]
): T | null | undefined {
const str = decodeString(input)
if (str == null) return str
return enumValues.includes(str as any) ? str as T : undefined
}
/**
* Encodes anything as a JSON string.
*
* @param {Any} any The thing to be encoded
* @return {String} The JSON string representation of any
*/
export function encodeJson(
any: any | null | undefined
): string | null | undefined {
if (any == null) {
return any;
}
return JSON.stringify(any);
}
/**
* Decodes a JSON string into javascript
*
* If an array is provided, only the first entry is used.
*
* @param {String} input The JSON string representation
* @return {Any} The javascript representation
*/
export function decodeJson(
input: string | (string | null)[] | null | undefined
): any | null | undefined {
const jsonStr = getEncodedValue(input);
if (jsonStr == null) return jsonStr;
let result = null;
try {
result = JSON.parse(jsonStr);
} catch (e) {
/* ignore errors, returning undefined */
}
return result;
}
/**
* Encodes an array as a JSON string.
*
* @param {Array} array The array to be encoded
* @return {String[]} The array of strings to be put in the URL
* as repeated query parameters
*/
export function encodeArray(
array: (string | null)[] | null | undefined
): (string | null)[] | null | undefined {
if (array == null) {
return array;
}
return array;
}
/**
* Decodes an array or singular value and returns it as an array
* or undefined if falsy. Filters out undefined values.
*
* @param {String | Array} input The input value
* @return {Array} The javascript representation
*/
export function decodeArray(
input: string | (string | null)[] | null | undefined
): (string | null)[] | null | undefined {
const arr = getEncodedValueArray(input);
if (arr == null) return arr;
return arr;
}
/**
* Encodes a numeric array as a JSON string.
*
* @param {Array} array The array to be encoded
* @return {String[]} The array of strings to be put in the URL
* as repeated query parameters
*/
export function encodeNumericArray(
array: (number | null)[] | null | undefined
): (string | null)[] | null | undefined {
if (array == null) {
return array;
}
return array.map(String);
}
/**
* Decodes an array or singular value and returns it as an array
* or undefined if falsy. Filters out undefined and NaN values.
*
* @param {String | Array} input The input value
* @return {Array} The javascript representation
*/
export function decodeNumericArray(
input: string | (string | null)[] | null | undefined
): (number | null)[] | null | undefined {
const arr = decodeArray(input);
if (arr == null) return arr;
return arr.map((d) => (d === '' || d == null ? null : +d));
}
/**
* Encodes an array as a delimited string. For example,
* ['a', 'b'] -> 'a_b' with entrySeparator='_'
*
* @param array The array to be encoded
* @param entrySeparator The string used to delimit entries
* @return The array as a string with elements joined by the
* entry separator
*/
export function encodeDelimitedArray(
array: (string | null)[] | null | undefined,
entrySeparator = '_'
): string | null | undefined {
if (array == null) {
return array;
}
return array.join(entrySeparator);
}
/**
* Decodes a delimited string into javascript array. For example,
* 'a_b' -> ['a', 'b'] with entrySeparator='_'
*
* If an array is provided as input, only the first entry is used.
*
* @param {String} input The JSON string representation
* @param entrySeparator The array as a string with elements joined by the
* entry separator
* @return {Array} The javascript representation
*/
export function decodeDelimitedArray(
input: string | (string | null)[] | null | undefined,
entrySeparator = '_'
): (string | null)[] | null | undefined {
const arrayStr = getEncodedValue(input, true);
if (arrayStr == null) return arrayStr;
if (arrayStr === '') return [];
return arrayStr.split(entrySeparator);
}
/**
* Encodes a numeric array as a delimited string. (alias of encodeDelimitedArray)
* For example, [1, 2] -> '1_2' with entrySeparator='_'
*
* @param {Array} array The array to be encoded
* @return {String} The JSON string representation of array
*/
export const encodeDelimitedNumericArray = encodeDelimitedArray as (
array: (number | null)[] | null | undefined,
entrySeparator?: string
) => string | null | undefined;
/**
* Decodes a delimited string into javascript array where all entries are numbers
* For example, '1_2' -> [1, 2] with entrySeparator='_'
*
* If an array is provided as input, only the first entry is used.
*
* @param {String} jsonStr The JSON string representation
* @return {Array} The javascript representation
*/
export function decodeDelimitedNumericArray(
arrayStr: string | (string | null)[] | null | undefined,
entrySeparator = '_'
): (number | null)[] | null | undefined {
const decoded = decodeDelimitedArray(arrayStr, entrySeparator);
if (decoded == null) return decoded;
return decoded.map((d) => (d === '' || d == null ? null : +d));
}
/**
* Encode simple objects as readable strings. Works only for simple,
* flat objects where values are numbers, strings.
*
* For example { foo: bar, boo: baz } -> "foo-bar_boo-baz"
*
* @param {Object} object The object to encode
* @param {String} keyValSeparator="-" The separator between keys and values
* @param {String} entrySeparator="_" The separator between entries
* @return {String} The encoded object
*/
export function encodeObject(
obj: { [key: string]: string | null | number | undefined } | null | undefined,
keyValSeparator = '-',
entrySeparator = '_'
): string | null | undefined {
if (obj == null) return obj; // null or undefined
if (!Object.keys(obj).length) return ''; // {} case
return Object.keys(obj)
.map((key) => `${key}${keyValSeparator}${obj[key]}`)
.join(entrySeparator);
}
/**
* Decodes a simple object to javascript. Currently works only for simple,
* flat objects where values are strings.
*
* For example "foo-bar_boo-baz" -> { foo: bar, boo: baz }
*
* If an array is provided as input, only the first entry is used.
*
* @param {String} input The object string to decode
* @param {String} keyValSeparator="-" The separator between keys and values
* @param {String} entrySeparator="_" The separator between entries
* @return {Object} The javascript object
*/
export function decodeObject(
input: string | (string | null)[] | null | undefined,
keyValSeparator = '-',
entrySeparator = '_'
): { [key: string]: string } | null | undefined {
const objStr = getEncodedValue(input, true);
if (objStr == null) return objStr;
if (objStr === '') return {};
const obj: { [key: string]: string } = {};
const keyValSeparatorRegExp = new RegExp(`${keyValSeparator}(.*)`);
objStr.split(entrySeparator).forEach((entryStr) => {
const [key, value] = entryStr.split(keyValSeparatorRegExp);
obj[key] = value;
});
return obj;
}
/**
* Encode simple objects as readable strings. Alias of encodeObject.
*
* For example { foo: 123, boo: 521 } -> "foo-123_boo-521"
*
* @param {Object} object The object to encode
* @param {String} keyValSeparator="-" The separator between keys and values
* @param {String} entrySeparator="_" The separator between entries
* @return {String} The encoded object
*/
export const encodeNumericObject = encodeObject as (
obj: { [key: string]: number | null | undefined } | null | undefined,
keyValSeparator?: string,
entrySeparator?: string
) => string | null | undefined;
/**
* Decodes a simple object to javascript where all values are numbers.
* Currently works only for simple, flat objects.
*
* For example "foo-123_boo-521" -> { foo: 123, boo: 521 }
*
* If an array is provided as input, only the first entry is used.
*
* @param {String} input The object string to decode
* @param {String} keyValSeparator="-" The separator between keys and values
* @param {String} entrySeparator="_" The separator between entries
* @return {Object} The javascript object
*/
export function decodeNumericObject(
input: string | (string | null)[] | null | undefined,
keyValSeparator = '-',
entrySeparator = '_'
): { [key: string]: number | null | undefined } | null | undefined {
const decoded: { [key: string]: string } | null | undefined = decodeObject(
input,
keyValSeparator,
entrySeparator
);
if (decoded == null) return decoded;
// convert to numbers
const decodedNumberObj: { [key: string]: number | null | undefined } = {};
for (const key of Object.keys(decoded)) {
decodedNumberObj[key] = decodeNumber(decoded[key]);
}
return decodedNumberObj;
}