Skip to content

Commit

Permalink
Feat: Add loader while loading data and pagination for posts by autho…
Browse files Browse the repository at this point in the history
…r page
  • Loading branch information
cp-dharti-r committed May 6, 2024
1 parent 19ffdd3 commit 1c627a8
Show file tree
Hide file tree
Showing 9 changed files with 123 additions and 29 deletions.
9 changes: 8 additions & 1 deletion nuxt-frontend/components/Blog.vue
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@
:count="count"
:status="status"
/>
<div v-if="showLoader" class="py-10">
<img :src="loaderImage" class="h-20 w-full" />
</div>
<div
:class="
count == 0 || status == config.NOT_FOUND
Expand All @@ -33,15 +36,16 @@
</template>

<script setup>
import loaderImage from "@/assets/images/theme/loader.svg";
import Header from "@/components/partials/NewHeader.vue";
import config from "@/config";
import { useBlogListStore } from "@/stores/resources";
import { toRefs } from "vue";
const props = defineProps({
isResource: Boolean,
});
const showLoader = ref(false);
const { isResource } = toRefs(props);
const { $mixpanel } = useNuxtApp();
const posts = ref([]);
Expand Down Expand Up @@ -69,6 +73,8 @@ const handleScroll = () => {
return;
}
showLoader.value = true;
useAsyncData("paginate", () =>
store.loadPaginateResources(
config.SHOW_DRAFT_POSTS,
Expand All @@ -77,6 +83,7 @@ const handleScroll = () => {
postLimit,
),
).then(() => {
showLoader.value = false;
posts.value.push(...resources.value);
posts.value = Array.from(new Set(posts.value.map(JSON.stringify))).map(
JSON.parse,
Expand Down
1 change: 1 addition & 0 deletions nuxt-frontend/nuxt.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ export default defineNuxtConfig({
defaults: {
lastmod: new Date(),
},
exclude: ["/unsubscribe", "/thank-you", "/jobs/thank-you"],
sources: [config.API_BASE + "/api/sitemap"],
xsl: false,
xslTips: false,
Expand Down
2 changes: 1 addition & 1 deletion nuxt-frontend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
},
"devDependencies": {
"@babel/eslint-parser": "^7.22.15",
"@canopassoftware/nuxt-blog-kit": "^1.0.5",
"@canopassoftware/nuxt-blog-kit": "^1.0.6",
"@ivanv/vue-collapse-transition": "^1.0.2",
"@nuxt/devtools": "latest",
"@nuxtjs/sitemap": "^5.1.0",
Expand Down
29 changes: 26 additions & 3 deletions nuxt-frontend/pages/author/[slug].vue
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,9 @@
<div class="mb-6 md:mb-10">
<AuthorPosts :posts="posts" :mixpanel="mixpanel" />
</div>
<div v-if="showLoader" class="py-10">
<img :src="loaderImage" class="h-20 w-full" />
</div>
</div>
</section>
<BlogFooter
Expand All @@ -45,17 +48,20 @@
</template>

<script setup>
import loaderImage from "@/assets/images/theme/loader.svg";
import Header from "@/components/partials/NewHeader.vue";
import { useRoute } from "vue-router";
import config from "@/config";
import { useAuthorListStore } from "@/stores/author";
const showLoader = ref(false);
const { $mixpanel } = useNuxtApp();
const route = useRoute();
const slug = ref(route.params.slug);
const posts = ref([]);
const store = useAuthorListStore();
const resources = computed(() => store.items);
const count = computed(() => store.totalPosts);
const status = computed(() => store.status);
let postLimit = 10;
Expand All @@ -72,9 +78,26 @@ const handleScroll = () => {
window.innerHeight + document.documentElement.scrollTop >=
document.documentElement.offsetHeight - 100
) {
const oldCount = postLimit;
postLimit += 2;
posts.value.push(...resources.value.slice(oldCount, postLimit));
if (posts.value.length >= count.value) {
return;
}
showLoader.value = true;
useAsyncData("paginate", () =>
store.loadPaginateAuthorBlogs(
config.SHOW_DRAFT_POSTS,
slug.value,
posts.value.length,
postLimit,
),
).then(() => {
showLoader.value = false;
posts.value.push(...resources.value);
posts.value = Array.from(new Set(posts.value.map(JSON.stringify))).map(
JSON.parse,
);
});
}
};
Expand Down
42 changes: 41 additions & 1 deletion nuxt-frontend/stores/author/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { setPostFields } from "~/utils";
export const useAuthorListStore = defineStore("authors", {
state: () => {
return {
totalPosts: 0,
items: null,
status: 0,
error: null,
Expand Down Expand Up @@ -34,10 +35,11 @@ export const useAuthorListStore = defineStore("authors", {
.get(url)
.then((response) => {
let posts = [];
response.data.forEach((post) => {
response.data.posts.forEach((post) => {
posts.push(setPostFields(post));
});
this.items = posts;
this.totalPosts = response.data.count;
this.isLoading = false;
this.status = posts.length > 0 ? response.status : config.NOT_FOUND;
resolve();
Expand All @@ -50,5 +52,43 @@ export const useAuthorListStore = defineStore("authors", {
});
});
},

async loadPaginateAuthorBlogs(showDrafts, slug, start, limit) {
return new Promise((resolve, reject) => {
this.isLoading = true;
this.error = null;

let published = showDrafts ? "is_published=false" : "is_published=true";

const limitQuery = limit ? "&skip=" + start + "&limit=" + limit : "";

let url =
config.API_BASE +
"/api/posts/author/" +
slug +
"?" +
published +
limitQuery;

axios
.get(url)
.then((response) => {
let posts = [];
response.data.posts.forEach((post) => {
posts.push(setPostFields(post));
});
this.items = posts;
this.isLoading = false;
this.status = response.status;
resolve();
})
.catch((error) => {
this.error = error;
this.isLoading = false;
this.status = config.NOT_FOUND;
reject(error);
});
});
},
},
});
8 changes: 4 additions & 4 deletions nuxt-frontend/yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -1667,10 +1667,10 @@
"@babel/helper-validator-identifier" "^7.22.20"
to-fast-properties "^2.0.0"

"@canopassoftware/nuxt-blog-kit@^1.0.5":
version "1.0.5"
resolved "https://registry.yarnpkg.com/@canopassoftware/nuxt-blog-kit/-/nuxt-blog-kit-1.0.5.tgz#6b75b3982fc09e1effa14c62a1ca2dd631df515c"
integrity sha512-nIc7pebnErikHH8ER9+LEM55hAF9I1udo75e56G2Vd6nySzSX2crNav73yOpBH+u11NxUaHwpBnwshLfqSr7nQ==
"@canopassoftware/nuxt-blog-kit@^1.0.6":
version "1.0.6"
resolved "https://registry.yarnpkg.com/@canopassoftware/nuxt-blog-kit/-/nuxt-blog-kit-1.0.6.tgz#8c37cd6f3695a9409438b9028a12dc9c4e9255e9"
integrity sha512-Th+OahmBVV3T6JKyRFFzNpUuBXq5UWo/yVfiqJX07mEcOIAOXYjW+Zw0TF5oqiVZZU2iI7s0OquQoknEuVYuhw==
dependencies:
"@nuxt/kit" "^3.7.4"
"@pinia/nuxt" "^0.5.0"
Expand Down
25 changes: 21 additions & 4 deletions post/author.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,12 @@ func (repository *Repository) GetPostsByAuthor(c *gin.Context) {
return
}

new_posts := []Post{}
var PostData struct {
Posts []Post `json:"posts"`
Count int `json:"count"`
}

new_post := PostData
for _, post := range posts {

var tags []Tag
Expand All @@ -72,12 +77,24 @@ func (repository *Repository) GetPostsByAuthor(c *gin.Context) {
post.Tag = ""
post.Tags = tags

new_posts = append(new_posts, post)
new_post.Posts = append(new_post.Posts, post)
}

new_posts = repository.PreparePosts(new_posts)
new_post.Posts = repository.PreparePosts(new_post.Posts)

if skip == 0 {
publishQuery := ""
if isPublished {
publishQuery = "WHERE p.is_published = true"
}

err = repository.Db.Get(&new_post.Count, `SELECT COUNT(p.id)
FROM posts p
JOIN posts_author_links pa ON p.id = pa.post_id
JOIN authors a ON a.id = pa.author_id AND a.username = $1 `+publishQuery, username)
}

c.JSON(http.StatusOK, new_posts)
c.JSON(http.StatusOK, new_post)
}

func (repository *Repository) GetAuthorByPostId(id int) (error, Author) {
Expand Down
32 changes: 19 additions & 13 deletions post/index.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,34 +53,36 @@ func (repository *Repository) Get(c *gin.Context) {
Count int `json:"count"`
}

new_posts := PostData
err, new_posts.Posts = repository.GetPosts(false, isResource, isPublished, limit, skip)
new_post := PostData
err, new_post.Posts = repository.GetPosts(false, isResource, isPublished, limit, skip)
if err != nil {
c.AbortWithStatus(http.StatusInternalServerError)
return
}

if isResource && skip == 0 {
err, new_posts.FeaturedPosts = repository.GetPosts(true, isResource, isPublished, 6, 0)
err, new_post.FeaturedPosts = repository.GetPosts(true, isResource, isPublished, 6, 0)
if err != nil {
c.AbortWithStatus(http.StatusInternalServerError)
return
}
}

resourceQuery := ""
if isResource {
resourceQuery = "is_resource = true AND"
}
if skip == 0 {
resourceQuery := "is_resource = false AND"
if isResource {
resourceQuery = "is_resource = true AND"
}

publishQuery := ""
if isPublished {
publishQuery = "AND is_published = true"
}
publishQuery := ""
if isPublished {
publishQuery = "AND is_published = true"
}

err = repository.Db.Get(&new_posts.Count, `SELECT COUNT(id) FROM posts WHERE `+resourceQuery+` is_featured = false `+publishQuery)
err = repository.Db.Get(&new_post.Count, `SELECT COUNT(id) FROM posts WHERE `+resourceQuery+` is_featured = false `+publishQuery)
}

c.JSON(http.StatusOK, new_posts)
c.JSON(http.StatusOK, new_post)
}

func (repository *Repository) GetPosts(isFeatured, isResource, isPublished bool, limit, skip int) (error, []Post) {
Expand Down Expand Up @@ -184,6 +186,10 @@ func (repository *Repository) Show(c *gin.Context) {

func (repository *Repository) PreparePosts(posts []Post) []Post {

if len(posts) == 0 {
return posts
}

new_posts := repository.SetPostImageInPosts(posts)
new_posts = repository.SetAuthorWithImageInPosts(posts)

Expand Down
4 changes: 2 additions & 2 deletions post/models.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ type Post struct {
CreatedAt string `json:"created_at,omitempty"`
UpdatedAt string `json:"updated_at,omitempty"`
PublishedAt null.String `json:"published_at"`
Summary string `json:"summary,omitempty"`
Summary null.String `json:"summary,omitempty"`
BlogContent string `json:"blog_content,omitempty"`
MetaDescription string `json:"meta_description,omitempty"`
Toc null.String `json:"toc,omitempty"`
Expand Down Expand Up @@ -118,7 +118,7 @@ type RecommendedPost struct {
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
PublishedAt null.String `json:"published_at"`
Summary string `json:"summary"`
Summary null.String `json:"summary"`
BlogContent string `json:"blog_content"`
MetaDescription string `json:"meta_description"`
Toc null.String `json:"toc"`
Expand Down

0 comments on commit 1c627a8

Please sign in to comment.