forked from jeremydaly/dynamodb-toolbox
-
Notifications
You must be signed in to change notification settings - Fork 0
/
getKey.ts
58 lines (52 loc) · 1.46 KB
/
getKey.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
/**
* DynamoDB Toolbox: A simple set of tools for working with Amazon DynamoDB
* @author Jeremy Daly <jeremy@jeremydaly.com>
* @license MIT
*/
import validateTypes from './validateTypes.js'
import { error, transformAttr } from './utils.js'
// Get partitionKey/sortKey
export default () => (
data: any,
schema: any,
partitionKey: any,
sortKey: any
) => {
// TODO: Think about a better way to reference pk/sk - can it work with secondary indexes?
partitionKey = schema[partitionKey].map || partitionKey
sortKey = (schema[sortKey] && schema[sortKey].map) || sortKey || null
const validateType = validateTypes()
// TODO: Add tests for 0 values
const pk = data[partitionKey]
if (pk === undefined || pk === null || pk === '') {
error(
`'${partitionKey}'${
schema[partitionKey].alias ? ` or '${schema[partitionKey].alias}'` : ''
} is required`
)
}
const sk = data[sortKey]
if (sortKey && (sk === undefined || sk === null || sk === '')) {
error(
`'${sortKey}'${schema[sortKey].alias ? ` or '${schema[sortKey].alias}'` : ''} is required`
)
}
return Object.assign(
{
[partitionKey]: transformAttr(
schema[partitionKey],
validateType(schema[partitionKey], partitionKey, pk),
data
)
},
sortKey !== null
? {
[sortKey]: transformAttr(
schema[sortKey],
validateType(schema[sortKey], sortKey, sk),
data
)
}
: {}
)
}