Skip to content

Commit

Permalink
Update post api for recommended post
Browse files Browse the repository at this point in the history
  • Loading branch information
cp-ashish-k committed Feb 9, 2024
1 parent d99431f commit a3743f3
Show file tree
Hide file tree
Showing 3 changed files with 2,715 additions and 2,027 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ node_modules
/dist
.tmp/
.strapi-updater.json
.strapi

# local env files
.env
Expand Down
54 changes: 44 additions & 10 deletions admin/src/api/post/controllers/post.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,13 +29,46 @@ module.exports = createCoreController("api::post.post", ({ strapi }) => ({
},
},
});
entity.readingTime = getReadingTime(entity.content);

const recommandedPosts = await strapi.db.query("api::post.post").findMany({
select: ['title','published_on','tags','content','slug'],
where: {
$and: [
{
slug: { $ne: entity.slug },
},
{
is_resource: entity.is_resource,
},
],
},
sort: { published_on: "desc" },
populate: {
image:true,
author: {
populate: {
image: true,
},
},
},
});
recommandedPosts.forEach(post => {
post.readingTime=getReadingTime(post.content);
});

entity.recommandedPosts = recommandedPosts
.filter((post) => {
return entity.tags
.map((t) => t.name)
.some((r) => post.tags.map((t) => t.name).includes(r));
})

return this.transformResponse(entity);
},

async find(ctx) {
let posts = await strapi.entityService.findMany("api::post.post", {
filters: ctx.query.filters,
publicationState: ctx.query.publicationState,
sort: { published_on: "desc" },
populate: {
Expand All @@ -44,14 +77,7 @@ module.exports = createCoreController("api::post.post", ({ strapi }) => ({
image: true,
},
},
tags: true,
category: true,
image: true,
comments: {
populate: {
user: true,
},
},
},
});

Expand All @@ -60,7 +86,7 @@ module.exports = createCoreController("api::post.post", ({ strapi }) => ({
async getBlogByTagName(ctx) {
const { tag } = ctx.params;

let posts = await strapi.entityService.findMany("api::post.post", {
let posts = await strapi.db.query("api::post.post").findMany({
sort: { published_on: "desc" },
populate: {
author: {
Expand All @@ -69,7 +95,6 @@ module.exports = createCoreController("api::post.post", ({ strapi }) => ({
},
},
tags: true,
category: true,
image: true,
},
publicationState: "live",
Expand All @@ -84,3 +109,12 @@ module.exports = createCoreController("api::post.post", ({ strapi }) => ({
return this.transformResponse(posts);
},
}));

function getReadingTime(content) {
const WORDS_PER_MINUTE = 265;
if (!content) return;
const numberOfWords = content
.replace(/<\/?[^>]+(>|$)/g, "")
.split(/\s/g)?.length;
return Math.ceil(numberOfWords / WORDS_PER_MINUTE);
}
Loading

0 comments on commit a3743f3

Please sign in to comment.