forked from thomas4019/mongo-query-to-postgres-jsonb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathselect.js
65 lines (63 loc) · 1.88 KB
/
select.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
var util = require('./util.js')
var convert = function (fieldName, projection) {
// Empty projection returns full document
if (!projection) {
return fieldName
}
//var output = '';
var shellDoc = {}
var removals = []
Object.keys(projection).forEach(function(field) {
var path = field.split('.')
if (projection[field] === 1) {
var current = shellDoc
for (var i = 0; i < path.length; i++) {
var key = path[i]
if (i !== path.length - 1) {
current[key] = current[key] || {}
current = current[key]
} else {
current[key] = field
}
}
} else if (projection[field] === 0) {
if (field !== '_id') {
removals.push('#- ' + util.toPostgresPath(path))
}
} else {
console.error(`unexpected projection value ${projection[field]} for ${field}`)
}
//output += util.convertDotNotation(fieldName, field)
//output +=
})
if (Object.keys(shellDoc).length > 0 && typeof projection['_id'] === 'undefined') {
shellDoc['_id'] = '_id'
}
else if (projection['_id'] === 0) {
delete shellDoc['_id']
}
if (removals.length > 0 && Object.keys(shellDoc).length > 0) {
throw new Error('Projection cannot have a mix of inclusion and exclusion.')
}
function convertRecur(input) {
if (typeof input === 'string') {
return util.pathToText([fieldName].concat(input.split('.')), false)
} else {
var entries = []
for (var key in input) {
entries.push('\'' + key + '\'')
entries.push(convertRecur(input[key]))
}
return 'jsonb_build_object(' + entries.join(', ') + ')'
}
}
var out = Object.keys(shellDoc).length > 0 ? convertRecur(shellDoc) : fieldName
if (removals.length) {
out += ' ' + removals.join(' ')
}
if (out === fieldName){
return fieldName
}
return out + ' as ' + fieldName
}
module.exports = convert