-
Notifications
You must be signed in to change notification settings - Fork 4
/
build-logic.js
51 lines (42 loc) · 1.18 KB
/
build-logic.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
const constants = require(`./constants`)
function build(clauses, joinedBy = `\n`) {
const built = constants.clauseOrder.map(
key => ({
key,
ary: clauses[key],
}),
)
.filter(clause => clause.ary && clause.ary.length > 0)
.map(clause => reduceClauseArray(clause.ary, constants.clauseKeyToString[clause.key]))
.reduce((part1, part2) => combine(joinedBy, part1, part2))
return {
sql: built.sql,
values: built.values,
}
}
function reduceClauseArray(clause, clauseQueryString) {
const reducedClause = clause.reduce((combinedClause, clausePart) => {
if (clausePart.values) {
combinedClause.values = combinedClause.values.concat(clausePart.values)
}
const joinedBy = (combinedClause.sql && clausePart.joinedBy) ? clausePart.joinedBy : ` `
combinedClause.sql = (combinedClause.sql + joinedBy + clausePart.sql).trim()
return combinedClause
}, {
values: [],
sql: ``,
})
return {
values: reducedClause.values,
sql: (`${ clauseQueryString } ${ reducedClause.sql }`).trim(),
}
}
function combine(joinCharacter, part1, part2) {
return {
values: part1.values.concat(part2.values),
sql: part1.sql + joinCharacter + part2.sql,
}
}
module.exports = {
build,
}