2018-03-27 17:15:28 +02:00
|
|
|
'use strict';
|
|
|
|
|
|
|
|
/**
|
|
|
|
* GraphQL.js service
|
|
|
|
*
|
|
|
|
* @description: A set of functions similar to controller's actions to avoid code duplication.
|
|
|
|
*/
|
|
|
|
|
2018-03-30 17:05:24 +02:00
|
|
|
const policyUtils = require('strapi-utils').policy;
|
|
|
|
|
2018-03-28 18:40:59 +02:00
|
|
|
const fs = require('fs');
|
|
|
|
const path = require('path');
|
|
|
|
const _ = require('lodash');
|
2018-03-29 14:03:09 +02:00
|
|
|
const pluralize = require('pluralize');
|
2018-03-27 19:02:04 +02:00
|
|
|
const { makeExecutableSchema } = require('graphql-tools');
|
2018-04-02 16:31:27 +02:00
|
|
|
const GraphQLJSON = require('graphql-type-json');
|
|
|
|
|
2018-03-27 19:02:04 +02:00
|
|
|
|
|
|
|
module.exports = {
|
|
|
|
|
2018-03-30 17:05:24 +02:00
|
|
|
/**
|
|
|
|
* Receive an Object and return a string which is following the GraphQL specs.
|
|
|
|
*
|
|
|
|
* @return String
|
|
|
|
*/
|
|
|
|
|
2018-04-02 16:31:27 +02:00
|
|
|
formatGQL: function (fields, description = {}, model = {}, type = 'field') {
|
2018-03-30 17:05:24 +02:00
|
|
|
const typeFields = JSON.stringify(fields, null, 2).replace(/['",]+/g, '');
|
|
|
|
const lines = typeFields.split('\n');
|
|
|
|
|
|
|
|
// Try to add description for field.
|
|
|
|
if (type === 'field') {
|
|
|
|
return lines
|
|
|
|
.map((line, index) => {
|
|
|
|
if ([0, lines.length - 1].includes(index)) {
|
2018-04-02 16:31:27 +02:00
|
|
|
return ``;
|
2018-03-30 17:05:24 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
const split = line.split(':');
|
|
|
|
const attribute = _.trim(split[0]);
|
2018-04-02 16:31:27 +02:00
|
|
|
const info = description[attribute] || _.get(model, `attributes.${attribute}.description`);
|
2018-03-30 17:05:24 +02:00
|
|
|
|
|
|
|
if (info) {
|
|
|
|
return ` """\n ${info}\n """\n${line}`;
|
|
|
|
}
|
|
|
|
|
|
|
|
return line;
|
|
|
|
})
|
|
|
|
.join('\n');
|
|
|
|
}
|
|
|
|
|
2018-04-02 16:31:27 +02:00
|
|
|
|
|
|
|
return lines
|
|
|
|
.map((line, index) => {
|
|
|
|
if ([0, lines.length - 1].includes(index)) {
|
|
|
|
return ``;
|
|
|
|
}
|
|
|
|
|
|
|
|
return line;
|
|
|
|
})
|
|
|
|
.join('\n');
|
2018-03-30 17:05:24 +02:00
|
|
|
},
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Retrieve description from variable and return a string which follow the GraphQL specs.
|
|
|
|
*
|
|
|
|
* @return String
|
|
|
|
*/
|
|
|
|
|
2018-04-02 16:31:27 +02:00
|
|
|
getDescription: (description, model = {}) => {
|
2018-03-30 17:05:24 +02:00
|
|
|
const format = `"""\n`;
|
|
|
|
|
2018-04-02 16:31:27 +02:00
|
|
|
const str = _.get(description, `_description`) || description || model.description;
|
2018-03-30 17:05:24 +02:00
|
|
|
|
|
|
|
if (str) {
|
|
|
|
return `${format}${str}\n${format}`;
|
|
|
|
}
|
|
|
|
|
|
|
|
return ``;
|
|
|
|
},
|
|
|
|
|
2018-04-02 16:31:27 +02:00
|
|
|
convertToParams: (params) => {
|
|
|
|
return Object.keys(params).reduce((acc, current) => {
|
|
|
|
return Object.assign(acc, {
|
|
|
|
[`_${current}`]: params[current]
|
|
|
|
});
|
|
|
|
}, {});
|
|
|
|
},
|
|
|
|
|
2018-03-30 17:05:24 +02:00
|
|
|
/**
|
|
|
|
* Convert Strapi type to GraphQL type.
|
|
|
|
*
|
|
|
|
* @return String
|
|
|
|
*/
|
2018-03-28 18:40:59 +02:00
|
|
|
|
2018-03-31 18:55:08 +02:00
|
|
|
convertType: (attr = {}) => {
|
|
|
|
// Type.
|
|
|
|
if (attr.type) {
|
|
|
|
switch (attr.type) {
|
|
|
|
case 'string':
|
|
|
|
case 'text':
|
|
|
|
return 'String';
|
|
|
|
case 'boolean':
|
|
|
|
return 'Boolean';
|
|
|
|
case 'integer':
|
|
|
|
return 'Int';
|
|
|
|
default:
|
|
|
|
return 'String';
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
const ref = attr.model || attr.collection;
|
|
|
|
|
|
|
|
// Association.
|
|
|
|
if (ref && ref !== '*') {
|
|
|
|
// Add bracket or not.
|
|
|
|
const plural = !_.isEmpty(attr.collection);
|
|
|
|
const globalId = attr.plugin ?
|
|
|
|
strapi.plugins[attr.plugin].models[ref].globalId:
|
|
|
|
strapi.models[ref].globalId;
|
|
|
|
|
|
|
|
if (plural) {
|
|
|
|
return `[${globalId}]`;
|
|
|
|
}
|
|
|
|
|
|
|
|
return globalId;
|
2018-03-27 19:02:04 +02:00
|
|
|
}
|
|
|
|
},
|
|
|
|
|
2018-03-30 17:05:24 +02:00
|
|
|
/**
|
|
|
|
* Execute policies before the specified resolver.
|
|
|
|
*
|
|
|
|
* @return Promise or Error.
|
|
|
|
*/
|
|
|
|
|
2018-04-02 16:31:27 +02:00
|
|
|
composeResolver: async function (obj, options, context, _schema, plugin, name, isSingular) {
|
|
|
|
const params = {
|
|
|
|
model: name
|
|
|
|
};
|
|
|
|
|
|
|
|
const queryOpts = plugin ? { source: plugin } : {};
|
|
|
|
|
|
|
|
// Retrieve generic service from the Content Manager plugin.
|
|
|
|
const resolvers = strapi.plugins['content-manager'].services['contentmanager'];
|
|
|
|
|
|
|
|
// Extract custom resolver or _type description.
|
|
|
|
const { resolver: handler = {} } = _schema;
|
|
|
|
|
|
|
|
// Retrieve policies.
|
|
|
|
const policies = isSingular ?
|
|
|
|
_.get(handler, `Query.${pluralize.singular(name)}.policy`, []):
|
|
|
|
_.get(handler, `Query.${pluralize.plural(name)}.policy`, []);
|
|
|
|
|
|
|
|
// Retrieve resolver. It could be the custom resolver of the user
|
|
|
|
// or the shadow CRUD resolver (aka Content-Manager).
|
|
|
|
const resolver = (() => {
|
|
|
|
if (isSingular) {
|
|
|
|
return
|
|
|
|
_.get(handler, `Query.${pluralize.singular(name)}.resolver`,
|
|
|
|
resolvers.fetch({ ...params, id: options.id }, queryOpts)
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
const resolver = _.get(handler, `Query.${pluralize.plural(name)}.resolver`,
|
|
|
|
async () => {
|
|
|
|
const convertedParams = strapi.utils.models.convertParams(name, this.convertToParams(options));
|
|
|
|
const where = strapi.utils.models.convertParams(name, options.where || {});
|
|
|
|
|
|
|
|
// Content-Manager specificity.
|
|
|
|
convertedParams.skip = convertedParams.start;
|
|
|
|
convertedParams.query = where.where;
|
|
|
|
|
|
|
|
return resolvers.fetchAll(params, {...queryOpts, ...convertedParams});
|
|
|
|
}
|
|
|
|
);
|
|
|
|
|
|
|
|
return resolver;
|
|
|
|
})();
|
|
|
|
|
2018-03-30 17:05:24 +02:00
|
|
|
const policiesFn = [];
|
|
|
|
|
|
|
|
// Populate policies.
|
|
|
|
policies.forEach(policy => policyUtils.get(policy, plugin, policiesFn, 'GraphQL error'));
|
|
|
|
|
|
|
|
// Execute policies stack.
|
|
|
|
const policy = await strapi.koaMiddlewares.compose(policiesFn)(context);
|
|
|
|
|
|
|
|
// Policy doesn't always return errors but they update the current context.
|
|
|
|
if (_.isError(context.response.body) || _.get(context.response.body, 'isBoom')) {
|
|
|
|
return context.response.body;
|
|
|
|
}
|
|
|
|
|
|
|
|
// When everything is okay, the policy variable should be undefined
|
|
|
|
// so it will return the resolver instead.
|
2018-04-02 16:31:27 +02:00
|
|
|
|
|
|
|
// Note: The resolver can be a function or promise.
|
|
|
|
return policy || _.isFunction(resolver) ? resolver.call(null, obj, options, context) : resolver;
|
2018-03-30 17:05:24 +02:00
|
|
|
},
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Construct the GraphQL query & definition and apply the right resolvers.
|
|
|
|
*
|
|
|
|
* @return Object
|
|
|
|
*/
|
|
|
|
|
2018-03-30 17:33:04 +02:00
|
|
|
shadowCRUD: function (models, plugin) {
|
2018-03-31 18:55:08 +02:00
|
|
|
const initialState = { definition: ``, query: {}, resolver: { Query : {} } };
|
2018-03-27 19:02:04 +02:00
|
|
|
|
2018-03-29 14:03:09 +02:00
|
|
|
if (_.isEmpty(models)) {
|
|
|
|
return initialState;
|
|
|
|
}
|
|
|
|
|
2018-03-30 17:33:04 +02:00
|
|
|
return models.reduce((acc, name) => {
|
|
|
|
const model = plugin ?
|
|
|
|
strapi.plugins[plugin].models[name]:
|
|
|
|
strapi.models[name];
|
2018-03-27 19:02:04 +02:00
|
|
|
|
2018-03-29 14:03:09 +02:00
|
|
|
// Setup initial state with default attribute that should be displayed
|
|
|
|
// but these attributes are not properly defined in the models.
|
|
|
|
const initialState = {
|
2018-03-30 17:33:04 +02:00
|
|
|
[model.primaryKey]: 'String'
|
2018-03-29 14:03:09 +02:00
|
|
|
};
|
|
|
|
|
|
|
|
// Add timestamps attributes.
|
2018-03-30 17:33:04 +02:00
|
|
|
if (_.get(model, 'options.timestamps') === true) {
|
2018-03-29 14:03:09 +02:00
|
|
|
Object.assign(initialState, {
|
|
|
|
created_at: 'String',
|
|
|
|
updated_at: 'String'
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2018-03-30 17:33:04 +02:00
|
|
|
const globalId = model.globalId;
|
2018-04-02 16:31:27 +02:00
|
|
|
const _schema = _.cloneDeep(_.get(strapi.plugins, `graphql.config._schema.graphql`, {}));
|
2018-03-30 17:05:24 +02:00
|
|
|
|
|
|
|
// Retrieve user customisation.
|
2018-04-02 16:31:27 +02:00
|
|
|
const { _type = {} } = _schema;
|
2018-03-30 17:05:24 +02:00
|
|
|
|
2018-03-27 19:02:04 +02:00
|
|
|
// Convert our layer Model to the GraphQL DL.
|
2018-03-30 17:33:04 +02:00
|
|
|
const attributes = Object.keys(model.attributes)
|
2018-03-27 19:02:04 +02:00
|
|
|
.reduce((acc, attribute) => {
|
|
|
|
// Convert our type to the GraphQL type.
|
2018-03-31 18:55:08 +02:00
|
|
|
acc[attribute] = this.convertType(model.attributes[attribute]);
|
2018-03-27 19:02:04 +02:00
|
|
|
|
|
|
|
return acc;
|
2018-03-29 14:03:09 +02:00
|
|
|
}, initialState);
|
2018-03-27 19:02:04 +02:00
|
|
|
|
2018-04-02 16:31:27 +02:00
|
|
|
acc.definition += `${this.getDescription(_type[globalId], model)}type ${globalId} {${this.formatGQL(attributes, _type[globalId], model)}}\n\n`;
|
2018-03-27 19:02:04 +02:00
|
|
|
|
2018-03-28 18:40:59 +02:00
|
|
|
Object.assign(acc.query, {
|
2018-04-02 16:31:27 +02:00
|
|
|
[`${pluralize.plural(name)}(sort: String, limit: Int, start: Int, where: JSON)`]: `[${model.globalId}]`,
|
2018-03-30 17:33:04 +02:00
|
|
|
[`${pluralize.singular(name)}(id: String!)`]: model.globalId
|
2018-03-28 18:40:59 +02:00
|
|
|
});
|
2018-03-27 19:02:04 +02:00
|
|
|
|
2018-04-02 16:31:27 +02:00
|
|
|
// TODO:
|
2018-03-28 18:40:59 +02:00
|
|
|
// - Handle mutations.
|
2018-03-31 18:55:08 +02:00
|
|
|
_.merge(acc.resolver, {
|
|
|
|
Query : {
|
|
|
|
[pluralize.plural(name)]: (obj, options, context) => this.composeResolver(
|
2018-04-02 16:31:27 +02:00
|
|
|
obj,
|
|
|
|
options,
|
2018-03-31 18:55:08 +02:00
|
|
|
context,
|
2018-04-02 16:31:27 +02:00
|
|
|
_schema,
|
2018-03-31 18:55:08 +02:00
|
|
|
plugin,
|
2018-04-02 16:31:27 +02:00
|
|
|
name,
|
|
|
|
false
|
2018-03-31 18:55:08 +02:00
|
|
|
),
|
2018-04-02 16:31:27 +02:00
|
|
|
[pluralize.singular(name)]: (obj, options, context) => this.composeResolver(
|
|
|
|
obj,
|
|
|
|
options,
|
2018-03-31 18:55:08 +02:00
|
|
|
context,
|
2018-04-02 16:31:27 +02:00
|
|
|
_schema,
|
2018-03-31 18:55:08 +02:00
|
|
|
plugin,
|
2018-04-02 16:31:27 +02:00
|
|
|
name,
|
|
|
|
true
|
2018-03-31 18:55:08 +02:00
|
|
|
)
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
// Build associations queries.
|
2018-04-02 16:31:27 +02:00
|
|
|
(model.associations || []).forEach(association => {
|
2018-03-31 18:55:08 +02:00
|
|
|
if (association.nature === 'manyMorphToMany') {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (!acc.resolver[globalId]) {
|
|
|
|
acc.resolver[globalId] = {};
|
|
|
|
}
|
|
|
|
|
|
|
|
// TODO:
|
|
|
|
// - Handle limit, skip, etc options
|
|
|
|
_.merge(acc.resolver[globalId], {
|
|
|
|
[association.alias]: (obj, options, context) => {
|
|
|
|
// Construct parameters object to retrieve the correct related entries.
|
|
|
|
const params = {
|
|
|
|
model: association.model || association.collection,
|
|
|
|
};
|
|
|
|
|
|
|
|
const queryOpts = {
|
|
|
|
source: association.plugin
|
|
|
|
};
|
|
|
|
|
|
|
|
if (association.type === 'model') {
|
|
|
|
params.id = obj[association.alias];
|
|
|
|
} else {
|
|
|
|
// Get attribute.
|
|
|
|
const attr = association.plugin ?
|
|
|
|
strapi.plugins[association.plugin].models[association.collection].attributes[association.via]:
|
|
|
|
strapi.models[association.collection].attributes[association.via];
|
|
|
|
|
|
|
|
// Get refering model.
|
|
|
|
const ref = attr.plugin ?
|
|
|
|
strapi.plugins[attr.plugin].models[attr.model || attr.collection]:
|
|
|
|
strapi.models[attr.model || attr.collection];
|
|
|
|
|
|
|
|
// Construct the "where" query to only retrieve entries which are
|
|
|
|
// related to this entry.
|
|
|
|
queryOpts.query = {
|
|
|
|
[association.via]: obj[ref.primaryKey]
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
return association.model ?
|
|
|
|
resolvers.fetch(params, association.plugin):
|
|
|
|
resolvers.fetchAll(params, queryOpts)
|
|
|
|
}
|
|
|
|
});
|
2018-03-27 19:02:04 +02:00
|
|
|
});
|
|
|
|
|
2018-03-28 18:40:59 +02:00
|
|
|
return acc;
|
2018-03-29 14:03:09 +02:00
|
|
|
}, initialState);
|
2018-03-28 18:40:59 +02:00
|
|
|
},
|
|
|
|
|
2018-03-30 17:05:24 +02:00
|
|
|
/**
|
|
|
|
* Generate GraphQL schema.
|
|
|
|
*
|
|
|
|
* @return Schema
|
|
|
|
*/
|
|
|
|
|
2018-03-28 18:40:59 +02:00
|
|
|
generateSchema: function () {
|
|
|
|
// Generate type definition and query/mutation for models.
|
2018-03-30 17:33:04 +02:00
|
|
|
const shadowCRUD = strapi.plugins.graphql.config.shadowCRUD !== false ? (() => {
|
|
|
|
// Exclude core models.
|
|
|
|
const models = Object.keys(strapi.models).filter(model => model !== 'core_store');
|
|
|
|
|
|
|
|
// Reproduce the same pattern for each plugin.
|
|
|
|
return Object.keys(strapi.plugins).reduce((acc, plugin) => {
|
|
|
|
const { definition, query, resolver } = this.shadowCRUD(Object.keys(strapi.plugins[plugin].models), plugin);
|
|
|
|
|
|
|
|
// We cannot put this in the merge because it's a string.
|
2018-03-31 18:55:08 +02:00
|
|
|
acc.definition += definition || ``;
|
2018-03-30 17:33:04 +02:00
|
|
|
|
|
|
|
return _.merge(acc, {
|
|
|
|
query,
|
|
|
|
resolver
|
|
|
|
});
|
|
|
|
}, this.shadowCRUD(models));
|
|
|
|
})() : {};
|
2018-03-27 19:02:04 +02:00
|
|
|
|
2018-04-02 16:31:27 +02:00
|
|
|
// Extract custom definition, query or resolver.
|
|
|
|
const { definition, query, resolver } = strapi.plugins.graphql.config._schema.graphql;
|
2018-03-31 18:55:08 +02:00
|
|
|
|
2018-03-28 18:40:59 +02:00
|
|
|
// Build resolvers.
|
2018-03-31 18:55:08 +02:00
|
|
|
const resolvers = _.omitBy(_.merge(resolver, shadowCRUD.resolver), _.isEmpty) || {};
|
2018-03-27 19:02:04 +02:00
|
|
|
|
2018-04-02 16:31:27 +02:00
|
|
|
// Transform object to only contain function.
|
|
|
|
Object.keys(resolvers).reduce((acc, type) => {
|
|
|
|
return Object.keys(acc[type]).reduce((acc, resolver) => {
|
|
|
|
acc[type][resolver] = _.isFunction(acc[type][resolver]) ?
|
|
|
|
acc[type][resolver]:
|
|
|
|
acc[type][resolver].resolver;
|
|
|
|
|
|
|
|
return acc;
|
|
|
|
}, acc);
|
|
|
|
}, resolvers);
|
|
|
|
|
2018-03-29 14:03:09 +02:00
|
|
|
// Return empty schema when there is no model.
|
2018-03-31 18:55:08 +02:00
|
|
|
if (_.isEmpty(shadowCRUD.definition) && _.isEmpty(definition)) {
|
2018-03-29 14:03:09 +02:00
|
|
|
return {};
|
|
|
|
}
|
|
|
|
|
2018-03-27 19:02:04 +02:00
|
|
|
// Concatenate.
|
2018-03-31 18:55:08 +02:00
|
|
|
const typeDefs =
|
|
|
|
definition +
|
|
|
|
shadowCRUD.definition +
|
2018-04-02 16:31:27 +02:00
|
|
|
`type Query {${this.formatGQL(shadowCRUD.query, {}, null, 'query')}${query}}\n` +
|
|
|
|
this.addCustomScalar(resolvers);
|
2018-03-30 17:05:24 +02:00
|
|
|
|
|
|
|
console.log(typeDefs);
|
2018-03-28 18:40:59 +02:00
|
|
|
|
|
|
|
// Write schema.
|
|
|
|
this.writeGenerateSchema(typeDefs);
|
|
|
|
|
2018-03-27 19:02:04 +02:00
|
|
|
// Build schema.
|
|
|
|
const schema = makeExecutableSchema({
|
|
|
|
typeDefs,
|
|
|
|
resolvers,
|
|
|
|
});
|
|
|
|
|
2018-03-31 18:55:08 +02:00
|
|
|
// Temporary variable to store the entire GraphQL configuration.
|
|
|
|
delete strapi.plugins.graphql.config._schema.graphql;
|
|
|
|
|
2018-03-27 19:02:04 +02:00
|
|
|
return schema;
|
2018-03-28 18:40:59 +02:00
|
|
|
},
|
|
|
|
|
2018-04-02 16:31:27 +02:00
|
|
|
/**
|
|
|
|
* Add custom scalar type such as JSON.
|
|
|
|
*
|
|
|
|
* @return void
|
|
|
|
*/
|
|
|
|
|
|
|
|
addCustomScalar: (resolvers) => {
|
|
|
|
Object.assign(resolvers, {
|
|
|
|
JSON: GraphQLJSON
|
|
|
|
});
|
|
|
|
|
|
|
|
return `scalar JSON`;
|
|
|
|
},
|
|
|
|
|
2018-03-30 17:05:24 +02:00
|
|
|
/**
|
|
|
|
* Save into a file the readable GraphQL schema.
|
|
|
|
*
|
|
|
|
* @return void
|
|
|
|
*/
|
|
|
|
|
2018-03-28 18:40:59 +02:00
|
|
|
writeGenerateSchema(schema) {
|
2018-03-28 20:13:09 +02:00
|
|
|
// Disable auto-reload.
|
|
|
|
strapi.reload.isWatching = false;
|
|
|
|
|
2018-03-28 18:40:59 +02:00
|
|
|
const generatedFolder = path.resolve(strapi.config.appPath, 'plugins', 'graphql', 'config', 'generated');
|
|
|
|
|
|
|
|
// Create folder if necessary.
|
|
|
|
try {
|
|
|
|
fs.accessSync(generatedFolder, fs.constants.R_OK | fs.constants.W_OK);
|
|
|
|
} catch (err) {
|
|
|
|
if (err && err.code === 'ENOENT') {
|
|
|
|
fs.mkdirSync(generatedFolder);
|
|
|
|
} else {
|
|
|
|
console.error(err);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fs.writeFileSync(path.join(generatedFolder, 'schema.graphql'), schema);
|
2018-03-28 20:13:09 +02:00
|
|
|
|
|
|
|
strapi.reload.isWatching = true;
|
2018-03-27 19:02:04 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
};
|