-
Notifications
You must be signed in to change notification settings - Fork 0
/
convertRecord.js
43 lines (32 loc) · 940 Bytes
/
convertRecord.js
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
function convertRecord (input, mappings) {
const output = {}
const unusedKeys = new Set(Object.keys(input))
for (const field in mappings) {
const config = mappings[field]
if (typeof config === 'string') {
const value = input[config]
if (typeof value !== 'undefined') {
output[field] = value === '' ? null : value
}
unusedKeys.delete(config)
} else {
if (!config.discard) {
const value = config.convert(input)
if (typeof value !== 'undefined') {
output[field] = value
}
}
if (config.field) {
unusedKeys.delete(config.field)
}
if (config.fields) {
config.fields.forEach(inputField => unusedKeys.delete(inputField))
}
}
}
if (unusedKeys.size > 0) {
throw new Error(`input has unused keys remaining: ${[...unusedKeys].join(', ')}`)
}
return output
}
module.exports = convertRecord