fix: sort search results chronologically when no query is provided

This commit is contained in:
Hossein Mehrabi 2024-01-31 18:07:48 +03:30
parent f09d8255ad
commit d1745dcd64
No known key found for this signature in database
GPG Key ID: 45C04964191AFAA1
3 changed files with 13 additions and 1 deletions

View File

@ -10,6 +10,8 @@ export default async function handler(
query: { q = '', tags: tagsString = '', type: typeString = '' },
} = req
const query = Array.isArray(q) ? q.join(' ').trim() : q.trim()
const tags =
typeof tagsString === 'string'
? tagsString
@ -43,7 +45,7 @@ export default async function handler(
if (postTypes.length > 0) {
const response = await strapiApi.searchPosts({
tags,
query: Array.isArray(q) ? q.join(' ').trim() : q.trim(),
query,
types: postTypes as LPE.PostType[],
limit: 15,
skip: 0,
@ -52,6 +54,14 @@ export default async function handler(
result.posts.push(...(response.data ?? []))
}
if (query.trim().length === 0) {
result.posts = result.posts.sort(
(a, b) =>
+new Date((b.data as LPE.Post.Document).publishedAt || 0) -
+new Date((a.data as LPE.Post.Document).publishedAt || 0),
)
}
res.status(200).json({
data: result,
})

View File

@ -80,6 +80,7 @@ export const postTransformer: Transformer<
slug,
modifiedAt: publishedAt,
createdAt: publishedAt,
publishedAt,
coverImage,
tags,
content,

View File

@ -165,6 +165,7 @@ export namespace LPE {
createdAt: string | null
modifiedAt: string | null
publishedAt: string | null
type: typeof LPE.PostTypes.Article
}