-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathutils.ts
63 lines (58 loc) · 1.97 KB
/
utils.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
import { BuilderType } from './builder'
/** Map a variable to an AWS type */
export const getType = (variable: any) => {
const variableType = typeof variable
switch (variableType) {
case 'boolean': return 'BOOL'
case 'string': return 'S'
case 'number': return 'N'
case 'object': // Special cases
if (Buffer.isBuffer(variable)) { return 'B' }
// If none of the above, fallthrough to string
default: return 'S'
}
}
// Might want to separate this out to 'formatters' file in future
/** Format a value that is valid for query builder type */
export const formatValue = (builderType: BuilderType, value: any) => {
switch (builderType) {
case BuilderType.DynamoDB:
if (Array.isArray(value)) {
return {
L: value.map((val) => ({ [getType(val)]: val }))
}
} else {
const type = getType(value)
return { [type]: value }
}
case BuilderType.DocumentClient: // DocumentClient is already good to go, fallthrough
default:
return value
}
}
/** Simple way to check if the object is empty */
export const isEmpty = (object: object) => {
return (Object.keys(object).length === 0)
}
/** Create a chainable function from a void function */
export const chainable = <T extends any[], U>(fn: (...args: T) => void, weeSomething: U) => {
return (...args: T): U => {
fn(...args)
return weeSomething
}
}
/** Wrapper function for dynamo operations to concat all results pages */
interface IResultsType { LastEvaluatedKey?: object; [key: string]: any }
export async function getAllPages<T = {}>(func: (lastEvaluatedKey?: object) => Promise<T>): Promise<T> {
const fullResults: any = {}
let results: IResultsType = {}
do {
results = await func(results.LastEvaluatedKey)
if (fullResults.Items === undefined) {
fullResults.Items = results.Items
} else {
fullResults.Items = [...results.Items, ...fullResults.Items]
}
} while (results.LastEvaluatedKey)
return fullResults
}