This repository has been archived by the owner on Mar 1, 2022. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathnql.js
63 lines (48 loc) · 1.77 KB
/
nql.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
const mingo = require('mingo');
const nql = require('@nexes/nql-lang');
const mongoKnex = require('@nexes/mongo-knex');
const utils = require('./utils');
module.exports = (queryString, options = {}) => {
const api = {};
// Convert the string to tokens - useful for testing / debugging, maybe for validating?
api.lex = () => nql.lex(queryString);
// Parse converts to mongo JSON and caches the result
api.parse = function () {
if (!this.filter && queryString) {
this.filter = nql.parse(queryString);
if (options.transformer) {
this.filter = options.transformer(this.filter);
}
}
let overrides;
let defaults;
if (options.overrides) {
overrides = nql.parse(options.overrides);
}
if (options.defaults) {
defaults = nql.parse(options.defaults);
}
let mongoJSON = utils.mergeFilters(overrides, this.filter, defaults);
if (options.expansions) {
mongoJSON = utils.expandFilters(mongoJSON, options.expansions);
}
return mongoJSON;
};
// Use Mingo to apply the query to a JSON object
// @TODO rethink this naming
api.queryJSON = function (obj) {
this.query = this.query || new mingo.Query(api.parse());
return this.query.test(obj);
};
// Use MongoKnex to apply the query to a query builder object
api.querySQL = qb => mongoKnex(qb, api.parse(), options);
// Get back the original query string
api.toString = () => queryString;
// Alias parse as toJSON()
api.toJSON = api.parse;
return api;
};
module.exports.utils = {
mapQuery: require('@nexes/mongo-utils').mapQuery,
mapKeyValues: require('@nexes/mongo-utils').mapKeyValues
};