grapher/lib/query/nodes/collectionNode.js

74 lines
1.8 KiB
JavaScript
Raw Normal View History

2016-09-14 16:04:08 +03:00
import FieldNode from './fieldNode.js';
export default class CollectionNode {
constructor(collection, body, linkName) {
this.linkName = linkName;
this.nodes = [];
2016-09-22 12:01:47 +03:00
this.collection = collection;
2016-09-14 16:04:08 +03:00
this.body = body;
this.props = {};
this.parent = null;
2016-09-21 18:33:50 +03:00
this.linker = null;
2016-09-14 16:04:08 +03:00
}
get collectionNodes() {
return _.filter(this.nodes, n => n instanceof CollectionNode)
}
get fieldNodes() {
return _.filter(this.nodes, n => n instanceof FieldNode);
}
2016-09-16 19:22:12 +03:00
hasGlobalFieldNode() {
return !!_.find(this.fieldNodes, n => n.isGlobal());
}
2016-09-14 16:04:08 +03:00
/**
* @param node
2016-09-21 18:33:50 +03:00
* @param linker
2016-09-14 16:04:08 +03:00
*/
2016-09-21 18:33:50 +03:00
add(node, linker) {
2016-09-14 16:04:08 +03:00
node.parent = this;
2016-09-21 18:33:50 +03:00
node.linker = linker;
2016-09-14 16:04:08 +03:00
this.nodes.push(node);
}
/**
2016-09-16 19:22:12 +03:00
* @param filters
2016-09-14 16:04:08 +03:00
* @param options
*/
2016-09-16 19:22:12 +03:00
applyFields(filters, options) {
let hasAddedAnyField = false;
2016-09-14 16:04:08 +03:00
2016-09-16 19:22:12 +03:00
if (this.hasGlobalFieldNode()) {
return options.fields = undefined;
}
2016-09-16 19:22:12 +03:00
_.each(this.fieldNodes, n => {
hasAddedAnyField = true;
n.applyFields(options.fields)
});
// it will only get here if it has collectionNodes children
_.each(this.collectionNodes, (collectionNode) => {
let linker = collectionNode.linker;
2016-09-21 18:33:50 +03:00
if (linker && !linker.isVirtual()) {
options.fields[linker.linkStorageField] = 1;
2016-09-21 18:33:50 +03:00
hasAddedAnyField = true;
}
2016-09-16 19:22:12 +03:00
});
// if he selected filters, we should automatically add those fields
_.each(filters, (value, field) => {
hasAddedAnyField = true;
options.fields[field] = 1;
});
if (!hasAddedAnyField) {
options.fields = {_id: 1};
}
}
2016-09-14 16:04:08 +03:00
}