forked from LeanKit-Labs/seriate
-
Notifications
You must be signed in to change notification settings - Fork 0
/
asList.js
40 lines (37 loc) · 917 Bytes
/
asList.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
const _ = require( "lodash" );
function replaceParamWithList( key, values ) {
if ( !values || !values.length ) {
return "(SELECT 1 WHERE 0 = 1)";
}
return `(${ values
.map( function( value, index ) {
return `@${ key }${ index }`;
} )
.join( ", " ) })`;
}
module.exports = {
matchesParam( param ) {
return param.asList === true;
},
createParameter( val, key ) {
return ( val.val || [] ).map( function( value, index ) {
return {
key: key + index,
type: val.type,
value
};
} );
},
transformQuery( params, query ) {
return _( params )
.toPairs()
.filter( function( pair ) {
return pair[ 1 ].asList;
} )
.reduce( function( acc, pair ) {
const regex = new RegExp( `(\\(\\s*)?@${ pair[ 0 ] }\\b(\\s*\\))?`, "ig" );
const replacement = replaceParamWithList( pair[ 0 ], pair[ 1 ].val );
return acc.replace( regex, replacement );
}, query );
}
};