Skip to content

Commit

Permalink
fix: issue #2 search by relation slug (#3)
Browse files Browse the repository at this point in the history
* fix: issue #2 search by relation slug

* feat: expose flat scructure endpoint for comments
  • Loading branch information
cyp3rius authored Jul 21, 2020
1 parent 056c91f commit 22eaebe
Show file tree
Hide file tree
Showing 6 changed files with 82 additions and 34 deletions.
22 changes: 22 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,28 @@ Return a hierarchical tree structure of comments for specified instance of Conte
]
```

### Get Comments (flat structure)

`GET <host>/comments/<content-type>:<id>/flat`

Return a flat structure of comments for specified instance of Content Type like for example `Article` with `ID: 1`

**Example URL**: `https://localhost:1337/comments/article:1/flat`

**Example response body**

```
[
{
-- Comment Model fields ---
},
{
-- Comment Model fields ---
},
...
]
```

**Possible response codes**
- `200` - Successful. Response with list of comments (can be empty)
- `400` - Bad Request. Requested list for not valid / not existing Content Type
Expand Down
8 changes: 8 additions & 0 deletions config/routes.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,14 @@
"policies": []
}
},
{
"method": "GET",
"path": "/:relation/flat",
"handler": "comments.findAllFlat",
"config": {
"policies": []
}
},
{
"method": "PUT",
"path": "/:relation/comment/:commentId",
Expand Down
11 changes: 11 additions & 0 deletions controllers/comments.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,17 @@ module.exports = {
return await strapi.plugins.comments.services.comments.findAll(ctx.query, page)
},

findAllFlat: async (ctx) => {
const { params = {} } = ctx;
const { relation } = parseParams(params);
try {
return await strapi.plugins.comments.services.comments.findAllFlat(relation);
}
catch (e) {
throwError(ctx, e);
}
},

findAllInHierarchy: async (ctx) => {
const { params = {} } = ctx;
const { relation } = parseParams(params);
Expand Down
5 changes: 5 additions & 0 deletions models/comment.settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,11 @@
"type": "string",
"configurable": false
},
"relatedSlug": {
"type": "string",
"private": true,
"configurable": false
},
"related": {
"collection": "*",
"filter": "field",
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.0",
"version": "1.0.0-beta.1",
"description": "Strapi - Comments plugin",
"strapi": {
"name": "Comments",
Expand Down
68 changes: 35 additions & 33 deletions services/comments.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ const _ = require('lodash');
const { sanitizeEntity } = require('strapi-utils');
const BadWordsFilter = require('bad-words');
const PluginError = require('./utils/error');
const { isEmpty } = require('lodash');

/**
* comments.js service
Expand Down Expand Up @@ -85,42 +86,40 @@ module.exports = {
};
},

// Find comments and create relations tree
findAllInHierarchy: async (relation, startingFromId = null, dropBlockedThreads = false) => {
const [relationType, relationId] = (relation || '').split(':');
// Find comments in the flat structure
findAllFlat: async (relation) => {
const { pluginName, model } = extractMeta(strapi.plugins);
const entities = await strapi.query( model.modelName, pluginName).find({}, ['authorUser', 'related', 'reports'])
.then(results => relation ? results.filter(result => {
const { related } = result || {};
if (related && !_.isEmpty(related)) {
return _.find(related, item =>
(`${item.id}` === relationId) &&
(item.__contentType.toLowerCase() === relationType.toLowerCase())
);
}
return false;
}) : results
);
return buildNestedStructure(entities.map(_ => filterOurResolvedReports(sanitizeEntity(_, { model }))), startingFromId, 'threadOf', dropBlockedThreads);
let criteria = {};
if (relation) {
criteria = {
...criteria,
relatedSlug: relation,
};
}
const entities = await strapi.query( model.modelName, pluginName)
.find(criteria, ['authorUser', 'related', 'reports']);
return entities.map(_ => filterOurResolvedReports(sanitizeEntity(_, { model })));
},

// Find comments and create relations tree structure
findAllInHierarchy: async (relation, startingFromId = null, dropBlockedThreads = false) => {
const { service } = extractMeta(strapi.plugins);
const entities = await service.findAllFlat(relation);
return buildNestedStructure(entities, startingFromId, 'threadOf', dropBlockedThreads);
},

// Find single comment
findOne: async (id, relation) => {
const [relationType, relationId] = (relation || '').split(':');
const { pluginName, model } = extractMeta(strapi.plugins);
const entity = await strapi.query( model.modelName, pluginName).findOne({ id }, ['related', 'reports'])
.then(result => {
if (relation) {
const { related } = result || {};
if (related && !_.isEmpty(related)) {
if (_.find(related, resultItem => (resultItem.id.toString() === relationId) && (resultItem.__contentType.toLowerCase() === relationType.toLowerCase()))) {
return result;
}
return null;
}
}
return result;
});
let criteria = { id };
if (relation) {
criteria = {
...criteria,
relatedSlug: relation,
};
}
const entity = await strapi.query( model.modelName, pluginName)
.findOne(criteria, ['related', 'reports']);
return filterOurResolvedReports(sanitizeEntity(entity, { model }));
},

Expand All @@ -140,6 +139,7 @@ module.exports = {
const { pluginName, model } = extractMeta(strapi.plugins);
const entity = await strapi.query( model.modelName, pluginName).create({
...data,
relatedSlug: `${related.ref}:${related.refId}`,
related: parsedRelation
});
return sanitizeEntity(entity, { model });
Expand All @@ -149,14 +149,14 @@ module.exports = {

// Update a comment
update: async (id, relation, data) => {
const { content, reports } = data;
const { content } = data;
const { pluginName, service, model } = extractMeta(strapi.plugins);
const existingEntity = sanitizeEntity(await service.findOne(id, relation), { model });
if (isEqualEntity(existingEntity, data) && content) {
if (checkBadWords(content)) {
const entity = await strapi.query( model.modelName, pluginName).update(
{ id },
{ content, reports }
{ content }
);
return sanitizeEntity(entity, { model }) ;
}
Expand Down Expand Up @@ -204,7 +204,9 @@ 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 entitiesOnSameLevel = await service.findAllInHierarchy(null, entity.threadOf ? entity.threadOf.id : null)
const relatedEntity = !_.isEmpty(entity.related) ? _.first(entity.related) : null;
const relation = relatedEntity ? `${relatedEntity.__contentType.toLowerCase()}:${relatedEntity.id}` : null;
const entitiesOnSameLevel = await service.findAllInHierarchy(relation, entity.threadOf ? entity.threadOf.id : null)
const selectedEntity = filterOurResolvedReports(sanitizeEntity(entity, { model }));
return {
selected: {
Expand Down

0 comments on commit 22eaebe

Please sign in to comment.