graphql-paper
Version:
A flexible in-memory store based on a GraphQL Schema
58 lines (56 loc) • 3.08 kB
JavaScript
;
var findDocument = require('../store/find-document.js');
var extractObjectTypes = require('../graphql/extract-object-types.js');
var isDocument = require('../document/is-document.js');
var createDocument = require('../document/create-document.js');
var extractListType = require('../graphql/extract-list-type.js');
function createOperation(context, typename, documentPartial) {
var _ref;
const {
store,
schema
} = context;
const document = createDocument.createDocument(typename, documentPartial);
const gqlType = schema.getType(typename);
const gqlTypeFields = (_ref = (gqlType === null || gqlType === void 0 ? void 0 : gqlType.getFields) && (gqlType === null || gqlType === void 0 ? void 0 : gqlType.getFields())) !== null && _ref !== void 0 ? _ref : {};
// setup array of types if it doesn't already exist
store[typename] = store[typename] || [];
store[typename].push(document);
for (const fieldName in document) {
const field = gqlTypeFields[fieldName];
if (!field) {
continue;
}
const documentFieldValue = document[fieldName];
const possibleObjectTypes = extractObjectTypes.extractObjectTypes(schema, field.type);
const hasObjectReferences = possibleObjectTypes.length > 0;
const isSingularConnection = hasObjectReferences && !extractListType.extractListType(field.type);
if (!hasObjectReferences) {
document[fieldName] = documentFieldValue;
continue;
}
if (documentFieldValue != null) {
const connectionCandidates = Array.isArray(documentFieldValue) ? documentFieldValue : [documentFieldValue];
const connectionDocuments = connectionCandidates.map(candidate => {
const isExistingDocument = isDocument.isDocument(candidate) && findDocument.findDocument(store, candidate) !== undefined;
if (isExistingDocument || candidate === null) {
return candidate;
}
if (candidate && possibleObjectTypes.length > 1) {
throw new Error(`The "${typename}" with field "${fieldName}" is represented by multiple types: ${possibleObjectTypes.join(', ')}. Therefore, cannot create document automatically for: \n\n ${JSON.stringify(documentFieldValue, null, 2)}.\n\nUse the \`create\` operation within mutate to explicitly create this document with one of possible types (${possibleObjectTypes.join(', ')}) and assign the connection explictly.`);
}
const [fieldObjectType] = possibleObjectTypes;
const result = createOperation(context, fieldObjectType.name, candidate);
return result;
});
// Technically a singular connection field with multiple documents isn't
// allowed but this will be caught by the validations. The createOperation
// is only concerned with automatically creating documents that don't exist
document[fieldName] = isSingularConnection && connectionDocuments.length === 1 ? connectionDocuments[0] : connectionDocuments;
continue;
}
}
return document;
}
exports.createOperation = createOperation;
//# sourceMappingURL=create.js.map