UNPKG

graphql-paper

Version:

A flexible in-memory store based on a GraphQL Schema

59 lines (58 loc) 2.58 kB
import { getConnections } from './get-connections.mjs'; import { getDocumentKey } from './get-document-key.mjs'; import { extractListType } from '../graphql/extract-list-type.mjs'; import { extractObjectTypes } from '../graphql/extract-object-types.mjs'; import { isDocument } from './is-document.mjs'; import { nullDocument } from './null-document.mjs'; function collapseDocument(schema, document) { var connections = getConnections(document); var type = schema.getType(document.__typename); if (!type) { throw new Error("Could not find type ".concat(document.__typename, " in the GraphQL Schema")); } var fields = type.getFields(); var _loop = function _loop(fieldName) { var documentFieldValue = document[fieldName]; var field = fields[fieldName]; var hasObjectReferences = extractObjectTypes(schema, field.type).length > 0; var isListConnection = extractListType(field.type) && hasObjectReferences; var isSingularConnection = !extractListType(field.type) && hasObjectReferences; var isConnectionField = isListConnection || isSingularConnection; // skip non-connection fields if (!isConnectionField) { return 0; // continue } // skip undefined and null if (documentFieldValue === undefined || documentFieldValue === null) { return 0; // continue } // handle list of connected documents var connectedDocuments = Array.isArray(documentFieldValue) ? documentFieldValue : [documentFieldValue]; var connectionKeys = connectedDocuments.map(maybeDocument => { // include positional null documents in list if necessary maybeDocument = maybeDocument === null ? nullDocument : maybeDocument; if (!isDocument(maybeDocument)) { throw new Error("Expected document in array on field ".concat(fieldName, ", got:\n").concat(JSON.stringify(maybeDocument, null, 2))); } return getDocumentKey(maybeDocument); }); connections[fieldName] = connectionKeys; // remove the existing value, the key is considered represented as a connection delete document[fieldName]; }, _ret; for (var fieldName in fields) { _ret = _loop(fieldName); if (_ret === 0) continue; } } function collapseConnections(graphqlSchema, store) { for (var typeName in store) { var typeStore = store[typeName]; for (var document of typeStore) { collapseDocument(graphqlSchema, document); } } } export { collapseConnections, collapseDocument }; //# sourceMappingURL=collapse-connections.mjs.map