Skip to content

Commit

Permalink
Update posts api
Browse files Browse the repository at this point in the history
  • Loading branch information
kelvinkipruto committed Sep 27, 2023
1 parent 89a60bc commit 516a9d6
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 9 deletions.
9 changes: 8 additions & 1 deletion apps/codeforafrica/src/components/Articles/useArticles.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,14 @@ const fetcher = (url) => fetch(url).then((res) => res.json());

function useArticles(query) {
const queryParams = useFilterQuery(query);
const { data, error } = useSWR(`/api/v1/stories${queryParams}`, fetcher);
const path = "stories";
const queryParamsWithPath = queryParams
? `${queryParams}&path=${path}`
: `?path=${path}`;
const { data, error } = useSWR(
`/api/v1/posts${queryParamsWithPath}`,
fetcher,
);

return {
data,
Expand Down
14 changes: 7 additions & 7 deletions apps/codeforafrica/src/lib/data/utils/posts.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import formatDate from "@/codeforafrica/utils/formatDate";

export function formatPost(post, page) {
export function formatPost(post, path) {
const {
id,
title,
Expand All @@ -21,11 +21,11 @@ export function formatPost(post, page) {
includeTime: false,
month: "short",
}),
href: `/posts/${page}/${slug}`,
href: `/posts/${path}/${slug}`,
};
}

export async function getPosts(api, params, page) {
export async function getPosts(api, params, path) {
const { page: queryPage = 1, tag, q, where = {}, ...other } = params;
const options = {
limit: 9,
Expand All @@ -35,7 +35,7 @@ export async function getPosts(api, params, page) {
and: [
{
"tags.name": {
contains: page,
contains: path,
},
},
],
Expand Down Expand Up @@ -71,16 +71,16 @@ export async function getPosts(api, params, page) {
const {
docs: postList,
totalPages,
page: newPage,
page,
} = await api.getCollection("posts", options);

const posts = postList.map((post) => formatPost(post, page));
const posts = postList.map((post) => formatPost(post, path));

return {
posts,
pagination: {
count: totalPages,
page: newPage,
page,
},
};
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@ import { getPosts } from "@/codeforafrica/lib/data/utils/posts";
import api from "@/codeforafrica/lib/payload";

export default async function handler(req, res) {
const { path, ...other } = req.query;
if (!path) return res.status(500).json({ error: "path is required" });
try {
const data = await getPosts(api, req.query, "stories");
const data = await getPosts(api, other, path);
return res.json(data);
} catch (error) {
return res.status(500).json(error);
Expand Down

0 comments on commit 516a9d6

Please sign in to comment.