This repository has been archived by the owner on Jun 1, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
70 lines (57 loc) · 2 KB
/
index.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
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
'use strict'
// Create an array of `object`'s own property values.
const values = (object) => {
return Object.keys(object).map((key) => {
return object[key]
})
}
// Check if the type of `value` is `string | string[]`.
const isValidValueOfQuery = (value) => {
return (
typeof value === 'string' ||
(Array.isArray(value) &&
value.every((element) => typeof element === 'string'))
)
}
// Check if the type of `query` is `{ [key: any]: string | string[] }`.
const isValidQuery = (query) => {
return typeof query === 'object' && values(query).every(isValidValueOfQuery)
}
// Shallow copy if type of `value` is array.
const cloneIfArray = (value) => {
return Array.isArray(value) ? [...value] : value
}
// Format the parsed URL query with default values.
const formatUrlQuery = (parsedUrlQuery, format) => {
if (!isValidQuery(parsedUrlQuery)) {
throw new TypeError('parsedUrlQuery is not a valid object.')
}
if (!isValidQuery(format)) {
throw new TypeError('format is not a valid object.')
}
return Object.keys(format).reduce((formatted, key) => {
const defaultValue = cloneIfArray(format[key])
const actualValue = cloneIfArray(parsedUrlQuery[key] || '')
const isExpectedTypeArray = Array.isArray(defaultValue)
const isExpectedTypeString = !isExpectedTypeArray
const isActualTypeArray = Array.isArray(actualValue)
const isActualTypeString = !isActualTypeArray
const assignedValue = (() => {
if (isExpectedTypeString && isActualTypeString) {
return actualValue || defaultValue
}
if (isExpectedTypeString && isActualTypeArray) {
return actualValue[0] || defaultValue
}
if (isExpectedTypeArray && isActualTypeString) {
return actualValue ? [actualValue] : defaultValue
}
if (isExpectedTypeArray && isActualTypeArray) {
return actualValue.length ? actualValue : defaultValue
}
})()
formatted[key] = assignedValue
return formatted
}, {})
}
module.exports = formatUrlQuery