graphql-paper
Version:
A flexible in-memory store based on a GraphQL Schema
64 lines (63 loc) • 3.04 kB
JavaScript
import { isNonNullType } from 'graphql';
import { getConnections } from './get-connections.mjs';
import { findDocument } from '../store/find-document.mjs';
import { extractListType } from '../graphql/extract-list-type.mjs';
import { extractObjectTypes } from '../graphql/extract-object-types.mjs';
import { isNullDocument } from './null-document.mjs';
function createConnectionProxy(schema, store, document, options) {
var _options$writable;
var writable = (_options$writable = options === null || options === void 0 ? void 0 : options.writable) !== null && _options$writable !== void 0 ? _options$writable : false;
return new Proxy(document, {
get(document, prop) {
var _document$__typename, _type$getFields, _Reflect$get;
if (Reflect.has(document, prop) || typeof prop !== 'string') {
return Reflect.get(document, prop);
}
var type = schema.getType((_document$__typename = document.__typename) !== null && _document$__typename !== void 0 ? _document$__typename : '');
var field = type === null || type === void 0 ? void 0 : (_type$getFields = type.getFields()) === null || _type$getFields === void 0 ? void 0 : _type$getFields[prop];
var hasPossibleConnections = field && extractObjectTypes(schema, field.type).length > 0;
if (type && field && hasPossibleConnections) {
var isNonNull = isNonNullType(field.type);
var isSingularConnection = !extractListType(field.type) && hasPossibleConnections;
var connections = getConnections(document);
if (connections[prop] === null) {
return null;
} else if (!Array.isArray(connections[prop])) {
if (!isNonNull) {
return null;
} else if (isSingularConnection) {
return undefined;
} else {
if (!writable) {
return Object.freeze([]);
} else {
var writableDocumentsArray = [];
document[field.name] = writableDocumentsArray;
return writableDocumentsArray;
}
}
} else {
var connectedDocuments = connections[prop].map(key => {
return isNullDocument(key) ? null : findDocument(store, key);
});
if (isSingularConnection) {
var _connectedDocuments$;
// only one connection expected, otherwise null
return (_connectedDocuments$ = connectedDocuments[0]) !== null && _connectedDocuments$ !== void 0 ? _connectedDocuments$ : null;
} else {
return connectedDocuments;
}
}
}
return (_Reflect$get = Reflect.get(document, prop)) !== null && _Reflect$get !== void 0 ? _Reflect$get : null;
},
set(document, prop, value) {
if (!writable) {
throw new Error('Setting on data pulled from the store is not allowed, use the `mutate` method.');
}
return Reflect.set(document, prop, value);
}
});
}
export { createConnectionProxy };
//# sourceMappingURL=create-connection-proxy.mjs.map