Skip to content

Commit

Permalink
fix: relations & content types slugs
Browse files Browse the repository at this point in the history
  • Loading branch information
cyp3rius committed Nov 11, 2020
1 parent d3950bf commit b477c7e
Show file tree
Hide file tree
Showing 5 changed files with 50 additions and 40 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ Complete installation requirements are exact same as for Strapi itself and can b

**Supported Strapi versions**:

- Strapi v3.1.1 (recently tested)
- Strapi v3.1.4 (recently tested)
- Strapi v3.x

(This plugin may work with the older Strapi versions, but these are not tested nor officially supported at this time.)
Expand Down
8 changes: 6 additions & 2 deletions admin/src/components/ItemFooter/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,14 @@ import { faLink } from '@fortawesome/free-solid-svg-icons';
import CardItemRelation from './CardItemRelation';
import CardItemAuthor from './CardItemAuthor';
import Wrapper from './Wrapper';
import { isNil } from 'lodash';
import { first, isNil, upperFirst } from 'lodash';

const ENTITY_NAME_PARAMS = ['title', 'Title', 'subject', 'Subject', 'name', 'Name'];
const resolveEntityName = entity => ENTITY_NAME_PARAMS.map(_ => entity[_]).filter(_ => _)[0] || '';
const humanizePascalCase = str => {
const plainConversion = str.replace(/[A-Z]/g, letter => ` ${letter.toLowerCase()}`);
return upperFirst(first(plainConversion) === ' ' ? plainConversion.slice(1, plainConversion.length) : plainConversion);
};

const ItemFooter = ({ authorName, authorUser, related, created_at, isDetailedView }) => {
const formatAuthor = () => {
Expand All @@ -23,7 +27,7 @@ const ItemFooter = ({ authorName, authorUser, related, created_at, isDetailedVie
return moment(created_at).format("DD/MM/YYYY, HH:mm:ss");
}

const formatRelationType = () => !isNil(related) ? related.__contentType : '';
const formatRelationType = () => !isNil(related) ? humanizePascalCase(related.__contentType) : '';

const formatRelationName = () => !isNil(related) ? resolveEntityName(related) : '';

Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "strapi-plugin-comments",
"version": "1.0.0-beta.4",
"version": "1.0.0-beta.5",
"description": "Strapi - Comments plugin",
"strapi": {
"name": "Comments",
Expand Down
46 changes: 23 additions & 23 deletions services/comments.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
'use strict';

const _ = require('lodash');
const { sanitizeEntity } = require('strapi-utils');
const { first, isEmpty, isNil } = require('lodash');
const PluginError = require('./utils/error');
const { isEqualEntity, extractMeta, buildNestedStructure, checkBadWords, filterOurResolvedReports } = require('./utils/functions');
const { isEqualEntity, extractMeta, buildNestedStructure, checkBadWords, filterOurResolvedReports, convertContentTypeNameToSlug } = require('./utils/functions');

/**
* comments.js service
Expand All @@ -12,18 +11,19 @@ const { isEqualEntity, extractMeta, buildNestedStructure, checkBadWords, filterO
*/

module.exports = {

// Find all comments
findAll: async (query) => {
const { pluginName, model } = extractMeta(strapi.plugins);
const paginationEnabled = !_.isNil(query._start);
const paginationEnabled = !isNil(query._start);
const params = {
...query,
_sort: paginationEnabled ? query._sort || 'created_at:desc' : undefined
};
const entities = query._q ?
await strapi.query( model.modelName, pluginName).search(params, ['authorUser', 'related', 'reports']) :
await strapi.query( model.modelName, pluginName).find(params, ['authorUser', 'related', 'reports']);
const items = entities.map(_ => filterOurResolvedReports(sanitizeEntity(_, { model })));
const items = entities.map(_ => filterOurResolvedReports(_));
const total = paginationEnabled ?
query._q ?
await strapi.query( model.modelName, pluginName).countSearch(params) :
Expand All @@ -48,7 +48,7 @@ module.exports = {
}
const entities = await strapi.query( model.modelName, pluginName)
.find(criteria, ['authorUser', 'related', 'reports']);
return entities.map(_ => filterOurResolvedReports(sanitizeEntity(_, { model })));
return entities.map(_ => filterOurResolvedReports(_));
},

// Find comments and create relations tree structure
Expand All @@ -70,7 +70,7 @@ module.exports = {
}
const entity = await strapi.query( model.modelName, pluginName)
.findOne(criteria, ['related', 'reports']);
return filterOurResolvedReports(sanitizeEntity(entity, { model }));
return filterOurResolvedReports(entity);
},

// Create a comment
Expand All @@ -79,21 +79,21 @@ module.exports = {
const { service, model } = extractMeta(strapi.plugins);
const parsedRelation = related && related instanceof Array ? related : [related];
const singleRelationFulfilled = related && (parsedRelation.length === 1);
const linkToThread = data.threadOf ? !!sanitizeEntity(await service.findOne(data.threadOf, relation), { model }) : true;
const linkToThread = data.threadOf ? !!await service.findOne(data.threadOf, relation) : true;

if (!linkToThread) {
throw new PluginError(400, 'Thread is not existing');
}

if (checkBadWords(content) && singleRelationFulfilled) {
const { pluginName, model } = extractMeta(strapi.plugins);
const relatedEntity = !_.isEmpty(related) ? _.first(related) : null;
const relatedEntity = !isEmpty(related) ? first(related) : null;
const entity = await strapi.query( model.modelName, pluginName).create({
...data,
relatedSlug: relatedEntity ? `${relatedEntity.ref}:${relatedEntity.refId}` : relation,
related: parsedRelation
});
return sanitizeEntity(entity, { model });
return entity;
}
throw new PluginError(400, 'No content received.');
},
Expand All @@ -102,14 +102,14 @@ module.exports = {
update: async (id, relation, data) => {
const { content } = data;
const { pluginName, service, model } = extractMeta(strapi.plugins);
const existingEntity = sanitizeEntity(await service.findOne(id, relation), { model });
const existingEntity = await service.findOne(id, relation);
if (isEqualEntity(existingEntity, data) && content) {
if (checkBadWords(content)) {
const entity = await strapi.query( model.modelName, pluginName).update(
{ id },
{ content }
);
return sanitizeEntity(entity, { model }) ;
return entity;
}
}
throw new PluginError(409, 'Action on that entity is not allowed');
Expand All @@ -118,15 +118,15 @@ module.exports = {
// Points up for comment
pointsUp: async (id, relation) => {
const { pluginName, service, model } = extractMeta(strapi.plugins);
const existingEntity = sanitizeEntity(await service.findOne(id, relation), { model });
const existingEntity = await service.findOne(id, relation);
if (existingEntity) {
const entity = await strapi.query( model.modelName, pluginName).update(
{ id },
{
points: (existingEntity.points || 0) + 1,
}
);
return sanitizeEntity(entity, { model }) ;
return entity;
}
throw new PluginError(409, 'Action on that entity is not allowed');
},
Expand All @@ -135,14 +135,14 @@ module.exports = {
reportAbuse: async (id, relation, payload) => {
const { pluginName, plugin, model, service } = extractMeta(strapi.plugins);
const { report: reportModel } = plugin.models;
const existingEntity = sanitizeEntity(await service.findOne(id, relation), { model });
const existingEntity = await service.findOne(id, relation);
if (existingEntity) {
const entity = await strapi.query(reportModel.modelName, pluginName).create({
...payload,
resolved: false,
related: id,
});
return sanitizeEntity(entity, { model: reportModel }) ;
return entity;
}
throw new PluginError(409, 'Action on that entity is not allowed');
},
Expand All @@ -155,16 +155,16 @@ module.exports = {
findOneAndThread: async (id) => {
const { pluginName, service, model } = extractMeta(strapi.plugins);
const entity = await strapi.query( model.modelName, pluginName).findOne({ id }, ['threadOf', 'threadOf.reports', 'authorUser', 'related', 'reports']);
const relatedEntity = !_.isEmpty(entity.related) ? _.first(entity.related) : null;
const relation = relatedEntity ? `${relatedEntity.__contentType.toLowerCase()}:${relatedEntity.id}` : null;
const relatedEntity = !isEmpty(entity.related) ? first(entity.related) : null;
const relation = relatedEntity ? `${convertContentTypeNameToSlug(relatedEntity.__contentType).toLowerCase()}:${relatedEntity.id}` : null;
const entitiesOnSameLevel = await service.findAllInHierarchy(relation, entity.threadOf ? entity.threadOf.id : null)
const selectedEntity = filterOurResolvedReports(sanitizeEntity(entity, { model }));
const selectedEntity = filterOurResolvedReports(entity);
return {
selected: {
...selectedEntity,
threadOf: selectedEntity.threadOf ? filterOurResolvedReports(selectedEntity.threadOf) : null,
},
level: entitiesOnSameLevel.map(_ => filterOurResolvedReports(sanitizeEntity(_, { model })))
level: entitiesOnSameLevel.map(_ => filterOurResolvedReports(_))
};
},

Expand All @@ -176,7 +176,7 @@ module.exports = {
{ id },
{ blocked: !existingEntity.blocked }
);
return sanitizeEntity(changedEntity, { model });
return changedEntity;
},

// Block / Unblock a comment thread
Expand All @@ -188,7 +188,7 @@ module.exports = {
{ blockedThread: !existingEntity.blockedThread }
);
await service.blockCommentThreadNested(id, !existingEntity.blockedThread)
return sanitizeEntity(changedEntity, { model });
return changedEntity;
},

blockCommentThreadNested: async (id, blockStatus) => {
Expand Down Expand Up @@ -222,6 +222,6 @@ module.exports = {
}, {
resolved: true,
});
return sanitizeEntity(entity, { model: reportModel }) ;
return entity;
},
};
32 changes: 19 additions & 13 deletions services/utils/functions.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,17 @@
const _ = require('lodash');
const BadWordsFilter = require('bad-words');
const PluginError = require('./error');
const { first, isObject } = require('lodash');

const buildNestedStructure = (entities, id = null, field = 'parent', dropBlockedThreads = false, blockNestedThreads = false) =>
entities
.filter(entity => (entity[field] === id) || (isObject(entity[field]) && (entity[field].id === id)))
.map(entity => ({
...entity,
[field]: undefined,
related: undefined,
blockedThread: blockNestedThreads || entity.blockedThread,
children: entity.blockedThread && dropBlockedThreads ? [] : buildNestedStructure(entities, entity.id, field, dropBlockedThreads, entity.blockedThread),
}));

module.exports = {
isEqualEntity: (existing, data) => {
Expand All @@ -23,17 +34,6 @@ module.exports = {
};
},

buildNestedStructure: (entities, id = null, field = 'parent', dropBlockedThreads = false, blockNestedThreads = false) =>
entities
.filter(entity => (entity[field] === id) || (_.isObject(entity[field]) && (entity[field].id === id)))
.map(entity => ({
...entity,
[field]: undefined,
related: undefined,
blockedThread: blockNestedThreads || entity.blockedThread,
children: entity.blockedThread && dropBlockedThreads ? [] : buildNestedStructure(entities, entity.id, field, dropBlockedThreads, entity.blockedThread),
})),

filterOurResolvedReports: item => (item ? {
...item,
reports: (item.reports || []).filter(report => !report.resolved),
Expand All @@ -50,5 +50,11 @@ module.exports = {
});
}
return content;
}
},
convertContentTypeNameToSlug: str => {
const plainConversion = str.replace(/[A-Z]/g, letter => `-${letter.toLowerCase()}`);
return first(plainConversion) === '-' ? plainConversion.slice(1, plainConversion.length) : plainConversion;
},

buildNestedStructure,
};

0 comments on commit b477c7e

Please sign in to comment.