-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathblog.ts
281 lines (232 loc) · 7.68 KB
/
blog.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
import type { PaginateFunction } from 'astro';
import { getCollection, render } from 'astro:content';
import type { CollectionEntry } from 'astro:content';
import type { Post } from '~/types';
import { APP_BLOG } from 'astrowind:config';
import { cleanSlug, trimSlash, BLOG_BASE, POST_PERMALINK_PATTERN, CATEGORY_BASE, TAG_BASE } from './permalinks';
const generatePermalink = async ({
id,
slug,
publishDate,
category,
}: {
id: string;
slug: string;
publishDate: Date;
category: string | undefined;
}) => {
const year = String(publishDate.getFullYear()).padStart(4, '0');
const month = String(publishDate.getMonth() + 1).padStart(2, '0');
const day = String(publishDate.getDate()).padStart(2, '0');
const hour = String(publishDate.getHours()).padStart(2, '0');
const minute = String(publishDate.getMinutes()).padStart(2, '0');
const second = String(publishDate.getSeconds()).padStart(2, '0');
const permalink = POST_PERMALINK_PATTERN.replace('%slug%', slug)
.replace('%id%', id)
.replace('%category%', category || '')
.replace('%year%', year)
.replace('%month%', month)
.replace('%day%', day)
.replace('%hour%', hour)
.replace('%minute%', minute)
.replace('%second%', second);
return permalink
.split('/')
.map((el) => trimSlash(el))
.filter((el) => !!el)
.join('/');
};
const getNormalizedPost = async (post: CollectionEntry<'post'>): Promise<Post> => {
const { id, data } = post;
const { Content, remarkPluginFrontmatter } = await render(post);
const {
publishDate: rawPublishDate = new Date(),
updateDate: rawUpdateDate,
title,
excerpt,
image,
tags: rawTags = [],
category: rawCategory,
author,
draft = false,
metadata = {},
} = data;
const slug = cleanSlug(id); // cleanSlug(rawSlug.split('/').pop());
const publishDate = new Date(rawPublishDate);
const updateDate = rawUpdateDate ? new Date(rawUpdateDate) : undefined;
const category = rawCategory
? {
slug: cleanSlug(rawCategory),
title: rawCategory,
}
: undefined;
const tags = rawTags.map((tag: string) => ({
slug: cleanSlug(tag),
title: tag,
}));
return {
id: id,
slug: slug,
permalink: await generatePermalink({ id, slug, publishDate, category: category?.slug }),
publishDate: publishDate,
updateDate: updateDate,
title: title,
excerpt: excerpt,
image: image,
category: category,
tags: tags,
author: author,
draft: draft,
metadata,
Content: Content,
// or 'content' in case you consume from API
readingTime: remarkPluginFrontmatter?.readingTime,
};
};
const load = async function (): Promise<Array<Post>> {
const posts = await getCollection('post');
const normalizedPosts = posts.map(async (post) => await getNormalizedPost(post));
const results = (await Promise.all(normalizedPosts))
.sort((a, b) => b.publishDate.valueOf() - a.publishDate.valueOf())
.filter((post) => !post.draft);
return results;
};
let _posts: Array<Post>;
/** */
export const isBlogEnabled = APP_BLOG.isEnabled;
export const isRelatedPostsEnabled = APP_BLOG.isRelatedPostsEnabled;
export const isBlogListRouteEnabled = APP_BLOG.list.isEnabled;
export const isBlogPostRouteEnabled = APP_BLOG.post.isEnabled;
export const isBlogCategoryRouteEnabled = APP_BLOG.category.isEnabled;
export const isBlogTagRouteEnabled = APP_BLOG.tag.isEnabled;
export const blogListRobots = APP_BLOG.list.robots;
export const blogPostRobots = APP_BLOG.post.robots;
export const blogCategoryRobots = APP_BLOG.category.robots;
export const blogTagRobots = APP_BLOG.tag.robots;
export const blogPostsPerPage = APP_BLOG?.postsPerPage;
/** */
export const fetchPosts = async (): Promise<Array<Post>> => {
if (!_posts) {
_posts = await load();
}
return _posts;
};
/** */
export const findPostsBySlugs = async (slugs: Array<string>): Promise<Array<Post>> => {
if (!Array.isArray(slugs)) return [];
const posts = await fetchPosts();
return slugs.reduce(function (r: Array<Post>, slug: string) {
posts.some(function (post: Post) {
return slug === post.slug && r.push(post);
});
return r;
}, []);
};
/** */
export const findPostsByIds = async (ids: Array<string>): Promise<Array<Post>> => {
if (!Array.isArray(ids)) return [];
const posts = await fetchPosts();
return ids.reduce(function (r: Array<Post>, id: string) {
posts.some(function (post: Post) {
return id === post.id && r.push(post);
});
return r;
}, []);
};
/** */
export const findLatestPosts = async ({ count }: { count?: number }): Promise<Array<Post>> => {
const _count = count || 4;
const posts = await fetchPosts();
return posts ? posts.slice(0, _count) : [];
};
/** */
export const getStaticPathsBlogList = async ({ paginate }: { paginate: PaginateFunction }) => {
if (!isBlogEnabled || !isBlogListRouteEnabled) return [];
return paginate(await fetchPosts(), {
params: { blog: BLOG_BASE || undefined },
pageSize: blogPostsPerPage,
});
};
/** */
export const getStaticPathsBlogPost = async () => {
if (!isBlogEnabled || !isBlogPostRouteEnabled) return [];
return (await fetchPosts()).flatMap((post) => ({
params: {
blog: post.permalink,
},
props: { post },
}));
};
/** */
export const getStaticPathsBlogCategory = async ({ paginate }: { paginate: PaginateFunction }) => {
if (!isBlogEnabled || !isBlogCategoryRouteEnabled) return [];
const posts = await fetchPosts();
const categories = {};
posts.map((post) => {
if (post.category?.slug) {
categories[post.category?.slug] = post.category;
}
});
return Array.from(Object.keys(categories)).flatMap((categorySlug) =>
paginate(
posts.filter((post) => post.category?.slug && categorySlug === post.category?.slug),
{
params: { category: categorySlug, blog: CATEGORY_BASE || undefined },
pageSize: blogPostsPerPage,
props: { category: categories[categorySlug] },
}
)
);
};
/** */
export const getStaticPathsBlogTag = async ({ paginate }: { paginate: PaginateFunction }) => {
if (!isBlogEnabled || !isBlogTagRouteEnabled) return [];
const posts = await fetchPosts();
const tags = {};
posts.map((post) => {
if (Array.isArray(post.tags)) {
post.tags.map((tag) => {
tags[tag?.slug] = tag;
});
}
});
return Array.from(Object.keys(tags)).flatMap((tagSlug) =>
paginate(
posts.filter((post) => Array.isArray(post.tags) && post.tags.find((elem) => elem.slug === tagSlug)),
{
params: { tag: tagSlug, blog: TAG_BASE || undefined },
pageSize: blogPostsPerPage,
props: { tag: tags[tagSlug] },
}
)
);
};
/** */
export async function getRelatedPosts(originalPost: Post, maxResults: number = 4): Promise<Post[]> {
const allPosts = await fetchPosts();
const originalTagsSet = new Set(originalPost.tags ? originalPost.tags.map((tag) => tag.slug) : []);
const postsWithScores = allPosts.reduce((acc: { post: Post; score: number }[], iteratedPost: Post) => {
if (iteratedPost.slug === originalPost.slug) return acc;
let score = 0;
if (iteratedPost.category && originalPost.category && iteratedPost.category.slug === originalPost.category.slug) {
score += 5;
}
if (iteratedPost.tags) {
iteratedPost.tags.forEach((tag) => {
if (originalTagsSet.has(tag.slug)) {
score += 1;
}
});
}
acc.push({ post: iteratedPost, score });
return acc;
}, []);
postsWithScores.sort((a, b) => b.score - a.score);
const selectedPosts: Post[] = [];
let i = 0;
while (selectedPosts.length < maxResults && i < postsWithScores.length) {
selectedPosts.push(postsWithScores[i].post);
i++;
}
return selectedPosts;
}