lunasqu.ee-nuxt/server/api/blog/index.ts

61 lines
1.4 KiB
TypeScript
Raw Normal View History

2022-10-16 16:17:55 +00:00
import { getFilteredBlogPosts } from '~~/lib/blog/read-posts';
2022-12-02 16:52:51 +00:00
import { BlogPost } from '~~/lib/types/post';
2022-10-16 09:37:13 +00:00
export default defineEventHandler(async (event) => {
const query = getQuery(event);
2022-12-02 16:52:51 +00:00
const include = (content: BlogPost) => {
2022-10-16 09:37:13 +00:00
const dateObj = new Date(content.date);
if (query.year) {
if (Number(query.year) !== dateObj.getFullYear()) {
return false;
}
}
if (query.month) {
if (Number(query.month) !== dateObj.getMonth() + 1) {
return false;
}
}
if (query.day) {
if (Number(query.day) !== dateObj.getDate()) {
return false;
}
}
2022-10-16 11:04:03 +00:00
if (query.tag) {
2022-12-02 16:52:51 +00:00
const tags = Array.isArray(query.tag) ? query.tag : [query.tag];
if (
!content.tags?.length ||
!tags.every((tag) => content.tags.includes(tag))
) {
2022-10-16 11:04:03 +00:00
return false;
}
}
2022-10-16 09:37:13 +00:00
return true;
};
2022-10-16 16:17:55 +00:00
const posts = await getFilteredBlogPosts(
2022-10-16 11:04:03 +00:00
include,
query.render !== 'false',
2022-10-16 12:50:21 +00:00
query.body === 'true'
2022-10-16 11:04:03 +00:00
);
2022-10-16 13:28:47 +00:00
const limit = Number(query.limit) || 10;
const pages = Math.ceil(posts.length / limit);
const page = Math.max(Math.min(Number(query.page) || 1, pages), 1);
const offset = (page - 1) * limit;
if (pages > 1) {
if (page + 1 <= pages) {
appendResponseHeader(event, 'X-Next-Page', (page + 1).toString());
}
appendResponseHeader(event, 'X-Last-Page', pages.toString());
}
return posts.slice(offset, offset + limit);
2022-10-16 09:37:13 +00:00
});