graphql-paper
Version:
A flexible in-memory store based on a GraphQL Schema
66 lines (64 loc) • 3.16 kB
JavaScript
;
var graphql = require('graphql');
var getConnections = require('./get-connections.js');
var findDocument = require('../store/find-document.js');
var extractListType = require('../graphql/extract-list-type.js');
var extractObjectTypes = require('../graphql/extract-object-types.js');
var nullDocument = require('./null-document.js');
function createConnectionProxy(schema, store, document, options) {
var _options$writable;
const 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);
}
const type = schema.getType((_document$__typename = document.__typename) !== null && _document$__typename !== void 0 ? _document$__typename : '');
const field = type === null || type === void 0 ? void 0 : (_type$getFields = type.getFields()) === null || _type$getFields === void 0 ? void 0 : _type$getFields[prop];
const hasPossibleConnections = field && extractObjectTypes.extractObjectTypes(schema, field.type).length > 0;
if (type && field && hasPossibleConnections) {
const isNonNull = graphql.isNonNullType(field.type);
const isSingularConnection = !extractListType.extractListType(field.type) && hasPossibleConnections;
const connections = getConnections.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 {
const writableDocumentsArray = [];
document[field.name] = writableDocumentsArray;
return writableDocumentsArray;
}
}
} else {
const connectedDocuments = connections[prop].map(key => {
return nullDocument.isNullDocument(key) ? null : findDocument.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);
}
});
}
exports.createConnectionProxy = createConnectionProxy;
//# sourceMappingURL=create-connection-proxy.js.map