-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
61 lines (52 loc) · 1.4 KB
/
index.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
const isObject = require('isobject');
function parse(query) {
if (typeof query !== 'string') {
return query;
}
try {
return JSON.parse(
query
.replace(/(?:\r\n|\r|\n)|,|:/g, ' ')
.replace(/([{}])/g, ' $1 ')
.replace(/ +/g, ' ')
.trim()
.replace(/([^ {}]+) /g, '"$1" ')
.replace(/" "/g, '":true, "')
.replace(/} "/g, '}, "')
.replace(/" {/g, '": {')
.replace(/" }/g, '":true }')
);
} catch (error) {
// eslint-disable-next-line no-console
console.error(`Invalid objectql query: ${query}`);
throw error;
}
}
module.exports = function objectql(source, query) {
if (!Array.isArray(source) && !isObject(source)) {
return source;
}
const parsedQuery = parse(query);
if (!isObject(parsedQuery)) {
return source;
}
if (Array.isArray(source)) {
return source.map(item => objectql(item, parsedQuery));
}
const sourceKeys = Object.keys(source);
return Object.keys(parsedQuery)
.filter(key => !!~sourceKeys.indexOf(key))
.reduce((newSource, key) => {
if (parsedQuery[key] === true) {
return Object.assign({}, newSource, {
[key]: source[key]
});
}
if (isObject(parsedQuery[key])) {
return Object.assign({}, newSource, {
[key]: objectql(source[key], parsedQuery[key])
});
}
return newSource;
}, {});
};