345 lines
12 KiB
JavaScript
Raw Normal View History

2018-06-27 19:00:19 +02:00
const _ = require('lodash');
const pluralize = require('pluralize');
module.exports = async cb => {
const pickData = (model) => _.pick(model, [
'info',
'connection',
'collectionName',
'attributes',
'identity',
'globalId',
'globalName',
'orm',
'loadedModel',
'primaryKey',
'associations'
]);
2018-07-23 15:12:33 +02:00
2018-07-26 13:33:57 +02:00
const pluginsLayout = Object.keys(strapi.plugins).reduce((acc, current) => {
const models = _.get(strapi.plugins, [current, 'config', 'layout'], {});
Object.keys(models).forEach(model => {
const layout = _.get(strapi.plugins, [current, 'config', 'layout', model], {});
acc[model] = layout;
});
return acc;
}, {});
2018-07-26 13:33:57 +02:00
const tempLayout = Object.keys(strapi.models)
.filter(m => m !== 'core_store')
.reduce((acc, current) => {
acc[current] = { attributes: {} };
return acc;
}, pluginsLayout);
2018-06-27 19:00:19 +02:00
const models = _.mapValues(strapi.models, pickData);
delete models['core_store'];
const pluginsModel = Object.keys(strapi.plugins).reduce((acc, current) => {
acc[current] = {
models: _.mapValues(strapi.plugins[current].models, pickData),
};
2018-07-23 15:12:33 +02:00
2018-06-27 19:00:19 +02:00
return acc;
}, {});
// Init schema
2018-06-28 17:54:24 +02:00
const schema = {
generalSettings: {
search: true,
filters: true,
bulkActions: true,
pageEntries: 10,
},
models: {
plugins: {},
},
2018-07-23 15:12:33 +02:00
layout: {}
2018-06-28 17:54:24 +02:00
};
2018-07-23 15:12:33 +02:00
2018-06-27 19:00:19 +02:00
const buildSchema = (model, name, plugin = false) => {
// Model data
2018-06-28 12:12:54 +02:00
const schemaModel = Object.assign({
2018-06-27 19:00:19 +02:00
label: _.upperFirst(name),
labelPlural: _.upperFirst(pluralize(name)),
orm: model.orm || 'mongoose',
2018-06-28 09:31:17 +02:00
search: true,
filters: true,
bulkActions: true,
2018-06-28 17:54:24 +02:00
pageEntries: 10,
defaultSort: model.primaryKey,
sort: 'ASC',
editDisplay: {
availableFields: {},
fields: [],
relations: [],
},
2018-06-28 12:12:54 +02:00
}, model);
const fieldsToRemove = [];
2018-06-27 19:00:19 +02:00
// Fields (non relation)
const fields = _.mapValues(_.pickBy(model.attributes, attribute =>
2018-06-27 19:00:19 +02:00
!attribute.model && !attribute.collection
), (value, attribute) => {
const fieldClassName = _.get(tempLayout, [name, 'attributes', attribute, 'className'], '');
if (fieldClassName === 'd-none') {
fieldsToRemove.push(attribute);
}
return {
label: _.upperFirst(attribute),
description: '',
type: value.type || 'string',
disabled: false,
};
});
// Don't display fields that are hidden by default like the resetPasswordToken for the model user
fieldsToRemove.forEach(field => {
_.unset(fields, field);
_.unset(schemaModel.attributes, field);
});
schemaModel.fields = fields;
schemaModel.editDisplay.availableFields = fields;
2018-07-23 15:12:33 +02:00
2018-06-27 19:00:19 +02:00
// Select fields displayed in list view
schemaModel.listDisplay = Object.keys(schemaModel.fields)
// Construct Array of attr ex { type: 'string', label: 'Foo', name: 'Foo', description: '' }
2018-06-28 09:31:17 +02:00
// NOTE: Do we allow sort on boolean?
2018-06-28 17:54:24 +02:00
.map(attr => {
const attrType = schemaModel.fields[attr].type;
const sortable = attrType !== 'json' && attrType !== 'array';
return Object.assign(schemaModel.fields[attr], { name: attr, sortable, searchable: sortable });
})
2018-06-27 19:00:19 +02:00
// Retrieve only the fourth first items
.slice(0, 4);
2018-07-23 15:12:33 +02:00
2018-06-28 12:12:54 +02:00
schemaModel.listDisplay.splice(0, 0, {
name: model.primaryKey || 'id',
label: 'Id',
type: 'string',
2018-06-28 17:54:24 +02:00
sortable: true,
searchable: true,
2018-06-28 12:12:54 +02:00
});
// This object will be used to customise the label and description and so on of an input.
// TODO: maybe add the customBootstrapClass in it;
schemaModel.editDisplay.availableFields = Object.keys(schemaModel.fields).reduce((acc, current) => {
// TODO: Add appearance in this object in order to get rid of the layout.json
acc[current] = Object.assign(
_.pick(_.get(schemaModel, ['fields', current], {}), ['label', 'type', 'description', 'name']),
{
editable: true,
placeholder: '',
});
return acc;
}, {});
2018-07-23 15:12:33 +02:00
2018-06-27 19:00:19 +02:00
if (model.associations) {
// Model relations
schemaModel.relations = model.associations.reduce((acc, current) => {
const label = _.upperFirst(current.alias);
const displayedAttribute = current.plugin ? // Value to modified to custom what's displayed in the react-select
2018-06-27 19:00:19 +02:00
_.get(pluginsModel, [current.plugin, 'models', current.model || current.collection, 'info', 'mainField']) ||
_.findKey(_.get(pluginsModel, [current.plugin, 'models', current.model || current.collection, 'attributes']), { type : 'string'}) ||
'id' :
_.get(models, [current.model || current.collection, 'info', 'mainField']) ||
_.findKey(_.get(models, [current.model || current.collection, 'attributes']), { type : 'string'}) ||
'id';
2018-07-23 15:12:33 +02:00
2018-06-27 19:00:19 +02:00
acc[current.alias] = {
...current,
description: '',
label,
2018-06-27 19:00:19 +02:00
displayedAttribute,
};
2018-07-23 15:12:33 +02:00
2018-06-27 19:00:19 +02:00
return acc;
}, {});
const relationsArray = Object.keys(schemaModel.relations).filter(relation => {
const isUploadRelation = _.get(schemaModel, ['relations', relation, 'plugin'], '') === 'upload';
const isMorphSide = _.get(schemaModel, ['relations', relation, 'nature'], '').toLowerCase().includes('morp') && _.get(schemaModel, ['relations', relation, relation]) !== undefined;
return !isUploadRelation && !isMorphSide;
});
const uploadRelations = Object.keys(schemaModel.relations).reduce((acc, current) => {
if (_.get(schemaModel, ['relations', current, 'plugin']) === 'upload') {
const model = _.get(schemaModel, ['relations', current]);
2018-07-23 15:12:33 +02:00
acc[current] = {
description: '',
editable: true,
label: _.upperFirst(current),
multiple: _.has(model, 'collection'),
name: current,
placeholder: '',
type: 'file',
disabled: false,
};
}
return acc;
}, {});
schemaModel.editDisplay.availableFields = _.merge(schemaModel.editDisplay.availableFields, uploadRelations);
schemaModel.editDisplay.relations = relationsArray;
2018-06-27 19:00:19 +02:00
}
schemaModel.editDisplay.fields = Object.keys(schemaModel.editDisplay.availableFields);
2018-07-23 15:12:33 +02:00
2018-06-27 19:00:19 +02:00
if (plugin) {
2018-06-28 17:54:24 +02:00
return _.set(schema.models.plugins, `${plugin}.${name}`, schemaModel);
2018-06-27 19:00:19 +02:00
}
2018-07-23 15:12:33 +02:00
2018-06-27 19:00:19 +02:00
// Set the formatted model to the schema
2018-06-28 17:54:24 +02:00
schema.models[name] = schemaModel;
2018-06-27 19:00:19 +02:00
};
2018-07-23 15:12:33 +02:00
2018-06-27 19:00:19 +02:00
_.forEach(pluginsModel, (plugin, pluginName) => {
_.forEach(plugin.models, (model, name) => {
buildSchema(model, name, pluginName);
});
});
2018-07-23 15:12:33 +02:00
2018-06-27 19:00:19 +02:00
// Generate schema for models.
_.forEach(models, (model, name) => {
buildSchema(model, name);
});
2018-07-23 15:12:33 +02:00
2018-06-27 19:00:19 +02:00
const pluginStore = strapi.store({
2018-06-28 12:12:54 +02:00
environment: '',
2018-06-27 19:00:19 +02:00
type: 'plugin',
name: 'content-manager'
});
const getApis = (data) => Object.keys(data).reduce((acc, curr) => {
if (data[curr].fields) {
return acc.concat([curr]);
}
2018-06-27 19:00:19 +02:00
if (curr === 'plugins') {
Object.keys(data[curr]).map(plugin => {
Object.keys(data[curr][plugin]).map(api => {
acc = acc.concat([`${curr}.${plugin}.${api}`]);
});
});
}
return acc;
2018-06-27 19:00:19 +02:00
}, []);
const getApisKeys = (data, sameArray) => sameArray.map(apiPath => {
const fields = Object.keys(_.get(data.models, apiPath.concat(['fields'])));
return fields.map(field => `${apiPath.join('.')}.fields.${field}`);
});
2018-07-23 15:12:33 +02:00
2018-07-27 17:24:58 +02:00
const getEditDisplayAvailableFieldsPath = attrPath => [..._.take(attrPath, attrPath.length -2), 'editDisplay', 'availableFields', attrPath[attrPath.length - 1]];
const getEditDisplayFieldsPath = attrPath => [..._.take(attrPath, attrPath.length -2), 'editDisplay', 'fields'];
2018-06-27 19:00:19 +02:00
try {
const prevSchema = await pluginStore.get({ key: 'schema' });
2018-06-27 19:00:19 +02:00
if (!prevSchema) {
_.set(schema, 'layout', tempLayout);
2018-07-23 15:12:33 +02:00
2018-06-27 19:00:19 +02:00
pluginStore.set({ key: 'schema', value: schema });
2018-07-23 15:12:33 +02:00
return cb();
2018-06-27 19:00:19 +02:00
}
const splitted = str => str.split('.');
const prevSchemaApis = getApis(prevSchema.models);
const schemaApis = getApis(schema.models);
const apisToAdd = schemaApis.filter(api => prevSchemaApis.indexOf(api) === -1).map(splitted);
const apisToRemove = prevSchemaApis.filter(api => schemaApis.indexOf(api) === -1).map(splitted);
const sameApis = schemaApis.filter(api => prevSchemaApis.indexOf(api) !== -1).map(splitted);
const schemaSameApisKeys = _.flattenDeep(getApisKeys(schema, sameApis));
const prevSchemaSameApisKeys = _.flattenDeep(getApisKeys(prevSchema, sameApis));
const sameApisAttrToAdd = schemaSameApisKeys.filter(attr => prevSchemaSameApisKeys.indexOf(attr) === -1).map(splitted);
const sameApisAttrToRemove = prevSchemaSameApisKeys.filter(attr => schemaSameApisKeys.indexOf(attr) === -1).map(splitted);
// Remove api
apisToRemove.map(apiPath => {
_.unset(prevSchema.models, apiPath);
});
2018-07-23 15:12:33 +02:00
// Remove API attribute
sameApisAttrToRemove.map(attrPath => {
2018-07-27 17:24:58 +02:00
const editDisplayPath = getEditDisplayAvailableFieldsPath(attrPath);
// Remove the field from the available fields in the editDisplayObject
_.unset(prevSchema.models, editDisplayPath);
// Check default sort and change it if needed
_.unset(prevSchema.models, attrPath);
const apiPath = attrPath.length > 3 ? _.take(attrPath, 3) : _.take(attrPath, 1);
const listDisplayPath = apiPath.concat('listDisplay');
const prevListDisplay = _.get(prevSchema.models, listDisplayPath);
const defaultSortPath = apiPath.concat('defaultSort');
const currentAttr = attrPath.slice(-1);
const defaultSort = _.get(prevSchema.models, defaultSortPath);
if (_.includes(currentAttr, defaultSort)) {
_.set(prevSchema.models, defaultSortPath, _.get(schema.models, defaultSortPath));
}
// Update the displayed fields
const updatedListDisplay = prevListDisplay.filter(obj => obj.name !== currentAttr.join());
if (updatedListDisplay.length === 0) {
// Update it with the one from the generaeted schema
_.set(prevSchema.models, listDisplayPath, _.get(schema.models, listDisplayPath, []));
} else {
_.set(prevSchema.models, listDisplayPath, updatedListDisplay);
}
});
// Add API
apisToAdd.map(apiPath => {
const api = _.get(schema.models, apiPath);
2018-07-06 13:21:50 +02:00
const { search, filters, bulkActions, pageEntries } = _.get(prevSchema, 'generalSettings');
_.set(api, 'filters', filters);
_.set(api, 'search', search);
_.set(api, 'bulkActions', bulkActions);
_.set(api, 'pageEntries', pageEntries);
_.set(prevSchema.models, apiPath, api);
});
2018-07-23 15:12:33 +02:00
// Add attribute to existing API
sameApisAttrToAdd.map(attrPath => {
const attr = _.get(schema.models, attrPath);
_.set(prevSchema.models, attrPath, attr);
2018-07-27 17:24:58 +02:00
// Add the field in the editDisplay object
const path = getEditDisplayAvailableFieldsPath(attrPath);
const availableAttrToAdd = _.get(schema.models, path);
_.set(prevSchema.models, path, availableAttrToAdd);
// Push the attr into the list
const fieldsPath = getEditDisplayFieldsPath(attrPath);
const currentFields = _.get(prevSchema.models, fieldsPath, []);
currentFields.push(availableAttrToAdd.name);
_.set(prevSchema.models, fieldsPath, currentFields);
});
// Update other keys
sameApis.map(apiPath => {
const keysToUpdate = ['relations', 'loadedModel', 'associations', 'attributes'].map(key => apiPath.concat(key));
keysToUpdate.map(keyPath => {
const newValue = _.get(schema.models, keyPath);
2018-07-23 15:12:33 +02:00
_.set(prevSchema.models, keyPath, newValue);
});
});
2018-07-05 17:57:30 +02:00
await pluginStore.set({ key: 'schema', value: prevSchema });
2018-06-27 19:00:19 +02:00
} catch(err) {
console.log('error', err);
2018-07-23 15:12:33 +02:00
}
2018-06-27 19:00:19 +02:00
cb();
2018-07-23 15:12:33 +02:00
};