-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathparameters.js
106 lines (95 loc) · 2.85 KB
/
parameters.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
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
const Key = require('./key')
/**
* Parameter wrapper
*/
class Parameters {
/**
* @param {string} [obj=null] "columnName"
* @param {object} [obj=null] {'column1': 1, 'column2': 2}
* @param {array} [obj=null] ['column1', 'column2']
*/
constructor(obj) {
this.obj = this.normalalizeObj(obj)
this.values = []
this.extra = {}
this.keyNames = []
if (Array.isArray(this.obj)) {
// ['field1', 'field2'] format
this.keyNames = this.obj
} else {
// {'field':'value'} format
Object.entries(this.obj).filter(
// Don't add fields starting with '_'. This is reserved for ordering / limit / offset.
entry => !entry[0].startsWith('_')
).forEach(entry => {
this.keyNames.push(entry[0])
this.values.push(entry[1])
})
}
this.isArray = this.keyNames.length > this.values.length
this.keys = this.keyNames.map(key => {
return new Key(key, this.isArray ? null : this.obj[key])
})
}
/**
* Convert object to valid value
* @param {string} obj "columnName"
* @param {object} obj {'column1': 1, 'column2': 2}
* @param {array} obj ['column1', 'column2']
* @returns {array} if array or string is given
* @returns {object} if object or null || undefined is given
*/
normalalizeObj(obj) {
if (!obj) {
return {}
}
if (typeof(obj) === 'string') {
return [obj]
}
return obj
}
/**
* Columns filtered by __eq should be indexed.
*
* @returns {array} column names which are filtered with __eq
*/
getIndexableColumnNames() {
return this.keys.filter(
(key) => key.filter === 'eq'
).map(
(key) => key.name
)
}
/**
* Get assignment string to be used in SQL queries.
*
* @param {string} [glue=", "]
* @returns {string} "column1" = ?, "column2" = ?
*/
getAssignString(glue) {
return this.keys.map(key => key.string).join(glue || ', ')
}
/**
* Get column string to be used in SQL queries
*
* @returns {string} "*" if no fields specified. Else '"column1", "column2"'
*/
getColumnString() {
if (this.keys.length === 0) {
return '*'
}
return '"' + this.keyNames.join('","') + '"'
}
/**
* Create comma devided question mark string with same length as columns to filter
*
* @returns {string} "?,?,?"
*/
getQuestionMarkString() {
return this.keys.filter(key => key.isParameter === true).map(() => '?').join(',')
}
getValues() {
return this.keys.filter(key => key.isParameter === true).map((key) => key.value)
}
}
module.exports = Parameters