494 lines
14 KiB
JavaScript
Raw Normal View History

'use strict';
/**
* GraphQL.js service
*
* @description: A set of functions similar to controller's actions to avoid code duplication.
*/
const _ = require('lodash');
2019-11-28 16:10:19 +01:00
const DynamicZoneScalar = require('../types/dynamiczoneScalar');
const Aggregator = require('./Aggregator');
const Query = require('./Query.js');
const Mutation = require('./Mutation.js');
const Types = require('./Types.js');
const Schema = require('./Schema.js');
const { toSingular, toPlural } = require('./naming');
const { mergeSchemas } = require('./utils');
2019-07-18 10:55:13 +02:00
const convertAttributes = (attributes, globalId) => {
return Object.keys(attributes)
.filter(attribute => attributes[attribute].private !== true)
.reduce((acc, attribute) => {
// Convert our type to the GraphQL type.
acc[attribute] = Types.convertType({
definition: attributes[attribute],
modelName: globalId,
attributeName: attribute,
});
return acc;
}, {});
2019-07-18 10:55:13 +02:00
};
2019-07-18 10:55:13 +02:00
const generateEnumDefinitions = (attributes, globalId) => {
return Object.keys(attributes)
.filter(attribute => attributes[attribute].type === 'enumeration')
.map(attribute => {
const definition = attributes[attribute];
2019-07-18 10:55:13 +02:00
const name = Types.convertEnumType(definition, globalId, attribute);
const values = definition.enum.map(v => `\t${v}`).join('\n');
return `enum ${name} {\n${values}\n}\n`;
})
2019-07-18 10:55:13 +02:00
.join('');
};
2019-11-28 15:33:37 +01:00
const generateDynamicZoneDefinitions = (attributes, globalId, schema) => {
Object.keys(attributes)
.filter(attribute => attributes[attribute].type === 'dynamiczone')
.forEach(attribute => {
const { components } = attributes[attribute];
const typeName = `${globalId}${_.upperFirst(
_.camelCase(attribute)
)}DynamicZone`;
if (components.length === 0) {
// Create dummy type because graphql doesn't support empty ones
2019-11-28 16:17:46 +01:00
schema.definition += `type ${typeName} { _:Boolean}`;
schema.definition += `\nscalar EmptyQuery\n`;
} else {
const componentsTypeNames = components.map(componentUID => {
const compo = strapi.components[componentUID];
if (!compo) {
throw new Error(
`Trying to creating dynamiczone type with unkown component ${componentUID}`
);
}
return compo.globalId;
});
const unionType = `union ${typeName} = ${componentsTypeNames.join(
' | '
)}`;
schema.definition += `\n${unionType}\n`;
}
2019-11-28 15:33:37 +01:00
const inputTypeName = `${typeName}Input`;
2019-11-28 16:17:46 +01:00
schema.definition += `\nscalar ${inputTypeName}\n`;
2019-11-28 15:33:37 +01:00
schema.resolvers[typeName] = {
__resolveType(obj) {
return strapi.components[obj.__component].globalId;
},
};
2019-11-28 16:10:19 +01:00
schema.resolvers[inputTypeName] = new DynamicZoneScalar({
2019-11-28 15:33:37 +01:00
name: inputTypeName,
2019-11-28 16:10:19 +01:00
attribute,
globalId,
components,
2019-11-28 15:33:37 +01:00
});
});
};
2019-10-01 17:45:16 +02:00
const mutateAssocAttributes = (associations = [], attributes) => {
2019-07-18 10:55:13 +02:00
associations
.filter(association => association.type === 'collection')
.forEach(association => {
2019-07-18 10:55:13 +02:00
attributes[
`${association.alias}(sort: String, limit: Int, start: Int, where: JSON)`
] = attributes[association.alias];
2019-07-18 10:55:13 +02:00
delete attributes[association.alias];
});
2019-07-18 10:55:13 +02:00
};
2019-12-10 16:21:21 +01:00
const buildAssocResolvers = model => {
2019-07-18 10:55:13 +02:00
const contentManager =
strapi.plugins['content-manager'].services['contentmanager'];
2019-07-18 10:55:13 +02:00
const { primaryKey, associations = [] } = model;
return associations
2019-11-28 15:33:37 +01:00
.filter(association => model.attributes[association.alias].private !== true)
.reduce((resolver, association) => {
2019-12-10 16:21:21 +01:00
const target = association.model || association.collection;
const targetModel = strapi.getModel(target, association.plugin);
2019-11-28 15:33:37 +01:00
switch (association.nature) {
2019-12-10 16:21:21 +01:00
case 'oneToManyMorph':
case 'manyMorphToOne':
case 'manyMorphToMany':
case 'manyToManyMorph': {
2019-11-28 15:33:37 +01:00
resolver[association.alias] = async obj => {
2019-12-10 16:21:21 +01:00
if (obj[association.alias]) {
return obj[association.alias];
}
2019-11-28 15:33:37 +01:00
const entry = await contentManager.fetch(
{
2019-07-18 10:55:13 +02:00
id: obj[primaryKey],
2019-12-10 16:21:21 +01:00
model: model.uid,
},
2019-11-28 15:33:37 +01:00
[association.alias]
);
2019-11-28 15:33:37 +01:00
return entry[association.alias];
};
2019-11-28 15:33:37 +01:00
break;
}
default: {
resolver[association.alias] = async (obj, options) => {
// Construct parameters object to retrieve the correct related entries.
const params = {
2019-12-10 16:21:21 +01:00
model: targetModel.uid,
2019-11-28 15:33:37 +01:00
};
2019-07-18 10:55:13 +02:00
2019-12-10 16:21:21 +01:00
let queryOpts = {};
2019-11-28 15:33:37 +01:00
if (association.type === 'model') {
2019-12-10 16:21:21 +01:00
params[targetModel.primaryKey] = _.get(
2019-11-28 15:33:37 +01:00
obj,
2019-12-10 16:21:21 +01:00
[association.alias, targetModel.primaryKey],
2019-10-01 17:56:52 +02:00
obj[association.alias]
2019-07-18 10:55:13 +02:00
);
} else {
2019-11-28 15:33:37 +01:00
const queryParams = Query.amountLimiting(options);
queryOpts = {
...queryOpts,
...Query.convertToParams(_.omit(queryParams, 'where')), // Convert filters (sort, limit and start/skip)
...Query.convertToQuery(queryParams.where),
};
if (
((association.nature === 'manyToMany' &&
association.dominant) ||
association.nature === 'manyWay') &&
_.has(obj, association.alias) // if populated
) {
_.set(
queryOpts,
2019-12-10 16:21:21 +01:00
['query', targetModel.primaryKey],
2019-11-28 15:33:37 +01:00
obj[association.alias]
? obj[association.alias]
2019-12-10 16:21:21 +01:00
.map(val => val[targetModel.primaryKey] || val)
2019-11-28 15:33:37 +01:00
.sort()
: []
);
} else {
_.set(
queryOpts,
['query', association.via],
2019-12-10 16:21:21 +01:00
obj[targetModel.primaryKey]
2019-11-28 15:33:37 +01:00
);
}
2019-07-18 10:55:13 +02:00
}
2019-11-28 15:33:37 +01:00
return association.model
? strapi.plugins.graphql.services.loaders.loaders[
2019-12-10 16:21:21 +01:00
targetModel.uid
2019-11-28 15:33:37 +01:00
].load({
params,
options: queryOpts,
single: true,
})
: strapi.plugins.graphql.services.loaders.loaders[
2019-12-10 16:21:21 +01:00
targetModel.uid
2019-11-28 15:33:37 +01:00
].load({
options: queryOpts,
association,
});
};
break;
}
2019-07-18 10:55:13 +02:00
}
2019-11-28 15:33:37 +01:00
return resolver;
}, {});
2019-07-18 10:55:13 +02:00
};
const buildModel = (model, { isComponent = false } = {}) => {
2019-07-18 10:55:13 +02:00
const { globalId, primaryKey } = model;
const schema = {
definition: '',
resolvers: {
[globalId]: {
id: obj => obj[primaryKey],
...buildAssocResolvers(model),
},
},
2019-11-28 15:33:37 +01:00
};
2019-07-18 10:55:13 +02:00
const initialState = {
id: 'ID!',
[primaryKey]: 'ID!',
};
if (_.isArray(_.get(model, 'options.timestamps'))) {
const [createdAtKey, updatedAtKey] = model.options.timestamps;
initialState[createdAtKey] = 'DateTime!';
initialState[updatedAtKey] = 'DateTime!';
}
const attributes = convertAttributes(model.attributes, globalId);
2019-10-01 17:45:16 +02:00
mutateAssocAttributes(model.associations, attributes);
2019-07-18 10:55:13 +02:00
_.merge(attributes, initialState);
2019-11-28 15:33:37 +01:00
schema.definition += generateEnumDefinitions(model.attributes, globalId);
generateDynamicZoneDefinitions(model.attributes, globalId, schema);
2019-07-18 10:55:13 +02:00
const description = Schema.getDescription({}, model);
const fields = Schema.formatGQL(attributes, {}, model);
const typeDef = `${description}type ${globalId} {${fields}}\n`;
2019-11-28 15:33:37 +01:00
schema.definition += typeDef;
schema.definition += Types.generateInputModel(model, globalId, {
2019-10-22 18:01:03 +02:00
allowIds: isComponent,
});
return schema;
};
/**
* Construct the GraphQL query & definition and apply the right resolvers.
*
* @return Object
*/
const buildShadowCRUD = models => {
const schema = {
definition: '',
query: {},
mutation: {},
2019-11-28 15:33:37 +01:00
resolvers: { Query: {}, Mutation: {} },
};
if (_.isEmpty(models)) {
return schema;
}
const subSchemas = Object.values(models).map(model => {
const { kind } = model;
switch (kind) {
case 'singleType': {
// const type = buildSingleType(model);
// mergeSubSchema(type, schema);
break;
}
default:
return buildCollectionType(model);
}
});
mergeSchemas(schema, ...subSchemas);
return schema;
};
const buildCollectionType = model => {
const { globalId, primaryKey, plugin, modelName } = model;
const singularName = toSingular(modelName);
const pluralName = toPlural(modelName);
const _schema = _.cloneDeep(
_.get(strapi.plugins, 'graphql.config._schema.graphql', {})
);
2019-07-17 13:13:07 +02:00
const { type = {}, resolver = {} } = _schema;
const localSchema = {
definition: '',
query: {},
mutation: {},
resolvers: { Query: {}, Mutation: {} },
};
// Setup initial state with default attribute that should be displayed
// but these attributes are not properly defined in the models.
const initialState = {
[primaryKey]: 'ID!',
id: 'ID!',
};
localSchema.resolvers[globalId] = {
// define the default id resolver
id(parent) {
return parent[model.primaryKey] || parent.id;
},
};
2019-07-18 10:55:13 +02:00
// Add timestamps attributes.
if (_.isArray(_.get(model, 'options.timestamps'))) {
const [createdAtKey, updatedAtKey] = model.options.timestamps;
initialState[createdAtKey] = 'DateTime!';
initialState[updatedAtKey] = 'DateTime!';
}
// Convert our layer Model to the GraphQL DL.
const attributes = convertAttributes(model.attributes, globalId);
mutateAssocAttributes(model.associations, attributes);
_.merge(attributes, initialState);
localSchema.definition += generateEnumDefinitions(model.attributes, globalId);
generateDynamicZoneDefinitions(model.attributes, globalId, localSchema);
const description = Schema.getDescription(type[globalId], model);
const fields = Schema.formatGQL(attributes, type[globalId], model);
const typeDef = `${description}type ${globalId} {${fields}}\n`;
localSchema.definition += typeDef;
// Add definition to the schema but this type won't be "queriable" or "mutable".
if (
type[model.globalId] === false ||
_.get(type, `${model.globalId}.enabled`) === false
) {
return localSchema;
}
const buildFindOneQuery = () => {
return _.get(resolver, `Query.${singularName}`) !== false
? Query.composeQueryResolver({
_schema,
plugin,
name: modelName,
isSingular: true,
})
: null;
};
const buildFindQuery = () => {
return _.get(resolver, `Query.${pluralName}`) !== false
? Query.composeQueryResolver({
_schema,
plugin,
name: modelName,
isSingular: false,
})
: null;
};
// Build resolvers.
const queries = {
singular: buildFindOneQuery(),
plural: buildFindQuery(),
};
if (_.isFunction(queries.singular)) {
_.merge(localSchema, {
query: {
[`${singularName}(id: ID!)`]: model.globalId,
},
resolvers: {
Query: {
[singularName]: queries.singular,
},
},
});
}
if (_.isFunction(queries.plural)) {
_.merge(localSchema, {
query: {
[`${pluralName}(sort: String, limit: Int, start: Int, where: JSON)`]: `[${model.globalId}]`,
},
resolvers: {
Query: {
[pluralName]: queries.plural,
},
},
});
}
// Add model Input definition.
localSchema.definition += Types.generateInputModel(model, modelName);
// build every mutation
['create', 'update', 'delete'].forEach(action => {
const mutationScheam = buildMutation({ model, action }, { _schema });
mergeSchemas(localSchema, mutationScheam);
});
// TODO: Add support for Graphql Aggregation in Bookshelf ORM
if (model.orm === 'mongoose') {
// Generation the aggregation for the given model
const modelAggregator = Aggregator.formatModelConnectionsGQL(
attributes,
model,
modelName,
queries.plural,
plugin
);
if (modelAggregator) {
localSchema.definition += modelAggregator.type;
if (!localSchema.resolvers[modelAggregator.globalId]) {
localSchema.resolvers[modelAggregator.globalId] = {};
2019-03-13 19:27:18 +01:00
}
_.merge(localSchema.resolvers, modelAggregator.resolver);
_.merge(localSchema.query, modelAggregator.query);
}
}
// Build associations queries.
_.assign(localSchema.resolvers[globalId], buildAssocResolvers(model));
return localSchema;
};
// TODO:
// - Implement batch methods (need to update the content-manager as well).
// - Implement nested transactional methods (create/update).
const buildMutation = ({ model, action }, { _schema }) => {
const capitalizedName = _.upperFirst(toSingular(model.modelName));
const mutationName = `${action}${capitalizedName}`;
const definition = Types.generateInputPayloadArguments({
model,
name: model.modelName,
mutationName,
action,
});
// ignore if disabled
if (_.get(_schema, ['resolver', 'Mutation', mutationName]) === false) {
return {
definition,
};
}
const mutationResolver = Mutation.composeMutationResolver({
_schema,
plugin: model.plugin,
name: model.modelName,
action,
});
return {
definition,
mutation: {
[`${mutationName}(input: ${mutationName}Input)`]: `${mutationName}Payload`,
},
resolvers: {
Mutation: {
[mutationName]: mutationResolver,
},
},
};
};
module.exports = {
buildShadowCRUD,
buildModel,
};