forked from share/sharedb-mingo-memory
-
Notifications
You must be signed in to change notification settings - Fork 0
/
get-query.js
31 lines (27 loc) · 979 Bytes
/
get-query.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
var cloneDeep = require('lodash.clonedeep');
// Given a key/value comparison query, return a query object with that
// filter and a specified sort order. The 'order' argument looks like
// [['foo', 1], ['bar', -1]] for sort by foo asending, then bar
// descending. This function is passed into the sharedb test suite.
function makeQuery(options) {
var inputQuery = options.query;
var sort = options.sort;
if (sort) {
// Convert sort order to Mongo's expected structure
if (!Array.isArray(sort)) throw new Error('invalid sort order');
if (sort.length > 0) {
var mongoSort = {};
for (var i = 0; i < sort.length; i++) {
if (!Array.isArray(sort[i]) || sort[i].length !== 2) {
throw new Error('invalid sort order');
}
mongoSort[sort[i][0]] = sort[i][1];
}
var query = cloneDeep(inputQuery);
query.$sort = mongoSort;
return query;
}
}
return inputQuery;
};
module.exports = makeQuery;