graphql-compose
Version:
GraphQL schema builder from different data sources with middleware extensions.
77 lines (66 loc) • 3.04 kB
JavaScript
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
/* eslint-disable no-param-reassign, no-lonely-if */
import { FIELD, FRAGMENT_SPREAD, INLINE_FRAGMENT } from 'graphql/language/kinds';
export function getProjectionFromAST(context, fieldNode) {
if (!context) {
return {};
}
var selections = void 0;
if (fieldNode) {
if (fieldNode.selectionSet) {
selections = fieldNode.selectionSet.selections;
}
} else if (Array.isArray(context.fieldNodes)) {
// get all selectionSets
selections = context.fieldNodes.reduce(function (result, source) {
if (source.selectionSet) {
result.push.apply(result, _toConsumableArray(source.selectionSet.selections));
}
return result;
}, []);
}
var projection = (selections || []).reduce(function (list, ast) {
switch (ast.kind) {
case FIELD:
list[ast.name.value] = getProjectionFromAST(context, ast) || true;
return list;
case INLINE_FRAGMENT:
return _extends({}, list, getProjectionFromAST(context, ast));
case FRAGMENT_SPREAD:
return _extends({}, list, getProjectionFromAST(context, context.fragments[ast.name.value]));
default:
throw new Error('Unsuported query selection');
}
}, {});
// this type params are setup via TypeComposer.addProjectionMapper()
// Sometimes, when you create relations you need query additional fields, that not in query.
// Eg. for obtaining `friendList` you also should add `friendIds` to projection.
if (projection && context.returnType) {
(function () {
var returnType = context.returnType;
while (returnType.ofType) {
returnType = returnType.ofType;
}
// $FlowFixMe
var mapper = returnType._gqcProjectionMapper;
if (mapper && (typeof mapper === 'undefined' ? 'undefined' : _typeof(mapper)) === 'object') {
Object.keys(mapper).forEach(function (key) {
if (projection[key]) {
Object.assign(projection, mapper[key]);
}
});
}
})();
}
return projection;
}
export function getFlatProjectionFromAST(context, fieldNodes) {
var projection = getProjectionFromAST(context, fieldNodes) || {};
var flatProjection = {};
Object.keys(projection).forEach(function (key) {
flatProjection[key] = !!projection[key];
});
return flatProjection;
}