refactor: improve type safety (#155)

* Fix to make it type safe.

* The build is failing, fix it.
This commit is contained in:
Katsuyuki Karasawa
2024-08-28 01:19:26 +09:00
committed by GitHub
parent f79ee3482d
commit e9c8930559
10 changed files with 489 additions and 133 deletions
+19 -13
View File
@@ -1,16 +1,22 @@
import { getCollection } from 'astro:content'
import type { BlogPostData } from '@/types/config'
import I18nKey from '@i18n/i18nKey'
import { i18n } from '@i18n/translation'
import { getCollection } from 'astro:content'
export async function getSortedPosts() {
const allBlogPosts = await getCollection('posts', ({ data }) => {
export async function getSortedPosts(): Promise<
{ data: BlogPostData; slug: string }[]
> {
const allBlogPosts = (await getCollection('posts', ({ data }) => {
return import.meta.env.PROD ? data.draft !== true : true
})
const sorted = allBlogPosts.sort((a, b) => {
const dateA = new Date(a.data.published)
const dateB = new Date(b.data.published)
return dateA > dateB ? -1 : 1
})
})) as unknown as { data: BlogPostData; slug: string }[]
const sorted = allBlogPosts.sort(
(a: { data: { published: Date } }, b: { data: { published: Date } }) => {
const dateA = new Date(a.data.published)
const dateB = new Date(b.data.published)
return dateA > dateB ? -1 : 1
},
)
for (let i = 1; i < sorted.length; i++) {
sorted[i].data.nextSlug = sorted[i - 1].slug
@@ -30,12 +36,12 @@ export type Tag = {
}
export async function getTagList(): Promise<Tag[]> {
const allBlogPosts = await getCollection('posts', ({ data }) => {
const allBlogPosts = await getCollection<'posts'>('posts', ({ data }) => {
return import.meta.env.PROD ? data.draft !== true : true
})
const countMap: { [key: string]: number } = {}
allBlogPosts.map(post => {
allBlogPosts.map((post: { data: { tags: string[] } }) => {
post.data.tags.map((tag: string) => {
if (!countMap[tag]) countMap[tag] = 0
countMap[tag]++
@@ -56,11 +62,11 @@ export type Category = {
}
export async function getCategoryList(): Promise<Category[]> {
const allBlogPosts = await getCollection('posts', ({ data }) => {
const allBlogPosts = await getCollection<'posts'>('posts', ({ data }) => {
return import.meta.env.PROD ? data.draft !== true : true
})
const count: { [key: string]: number } = {}
allBlogPosts.map(post => {
allBlogPosts.map((post: { data: { category: string | number } }) => {
if (!post.data.category) {
const ucKey = i18n(I18nKey.uncategorized)
count[ucKey] = count[ucKey] ? count[ucKey] + 1 : 1