-
Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy pathhandlePosts.ts
More file actions
238 lines (212 loc) · 7.01 KB
/
Copy pathhandlePosts.ts
File metadata and controls
238 lines (212 loc) · 7.01 KB
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
import { postViews } from "../db/schema.ts";
import { AppContext } from "../mod.ts";
import { BlogPost, SortBy, ViewFromDatabase } from "../types.ts";
import { VALID_SORT_ORDERS } from "../utils/constants.ts";
/**
* `BlogPost.date` may be a bare `YYYY-MM-DD` or a full ISO 8601 timestamp.
* A bare date is read as UTC midnight so ordering doesn't depend on the
* machine timezone. Unparseable values fall back to 0 instead of leaking NaN
* into the comparator (a NaN result is treated as 0, so the post never moves).
*/
const dateToTime = (date: string) =>
new Date(/^\d{4}-\d{2}-\d{2}$/.test(date) ? `${date}T00:00:00Z` : date)
.getTime() || 0;
/**
* Returns an sorted BlogPost list
*
* @param posts Posts to be sorted
* @param sortBy Sort option (must be: "date_desc" | "date_asc" | "title_asc" | "title_desc" | "view_asc" | "view_desc" )
*/
export const sortPosts = async (
blogPosts: BlogPost[],
sortBy: SortBy,
ctx: AppContext,
) => {
const splittedSort = sortBy.split("_");
if (splittedSort[0] === "view") {
//If sort is "view_asc" or "view_desc"
// deno-lint-ignore no-explicit-any
const records = await (ctx.invoke as any).records.loaders.drizzle();
//Deco records not installed
if (records.__resolveType) {
throw new Error("Deco Records not installed!");
}
//Get views from database
const views = await records.select({
id: postViews.id,
userInteractionCount: postViews.userInteractionCount,
}).from(postViews) as ViewFromDatabase[] | null;
if (!views) {
return blogPosts;
}
//Act like a real extension
for (let i = 0; i < views.length; i++) {
const view = views[i];
const post = blogPosts.findIndex(({ slug }) => slug === view.id);
if (blogPosts[post]) {
blogPosts[post].interactionStatistic = {
"@type": "InteractionCounter",
userInteractionCount: view.userInteractionCount,
};
}
}
const sortOrder = VALID_SORT_ORDERS.includes(splittedSort[1])
? splittedSort[1]
: "desc";
//Sort and return
return blogPosts.toSorted((a, b) => {
const countOfA = a?.interactionStatistic?.userInteractionCount;
const countOfB = b?.interactionStatistic?.userInteractionCount;
if (
!countOfA &&
!countOfB
) {
return 0;
}
const comparison = (countOfA ?? 0) - (countOfB ?? 0);
return sortOrder === "desc" ? comparison : -comparison;
});
}
const sortMethod = splittedSort[0] in blogPosts[0]
? splittedSort[0] as keyof BlogPost
: "date";
const sortOrder = VALID_SORT_ORDERS.includes(splittedSort[1])
? splittedSort[1]
: "desc";
return blogPosts.toSorted((a, b) => {
if (!a[sortMethod] && !b[sortMethod]) {
return 0; // If both posts don't have the sort method, consider them equal
}
if (!a[sortMethod]) {
return 1; // If post a doesn't have sort method, put it after post b
}
if (!b[sortMethod]) {
return -1; // If post b doesn't have sort method, put it after post a
}
const comparison = sortMethod === "date"
? dateToTime(b.date) - dateToTime(a.date)
: a[sortMethod]?.toString().localeCompare(
b[sortMethod]?.toString() ?? "",
) ?? 0;
return sortOrder === "desc" ? comparison : -comparison; // Invert sort depending of desc or asc
});
};
/**
* Returns an filtered BlogPost list
*
* @param posts Posts to be handled
* @param slug Category Slug to be filter
*/
export const filterPostsByCategory = (posts: BlogPost[], slug?: string) =>
slug
? posts.filter(({ categories }) => categories?.find((c) => c.slug === slug))
: posts;
/**
* Returns an filtered BlogPost list by specific slugs
*
* @param posts Posts to be handled
* @param postSlugs Specific slugs to be filter
*/
export const filterPostsBySlugs = (posts: BlogPost[], postSlugs: string[]) =>
posts.filter(({ slug }) => postSlugs.includes(slug));
/**
* Returns an filtered BlogPost list
*
* @param posts Posts to be handled
* @param term Term to be filter
*/
export const filterPostsByTerm = (posts: BlogPost[], term: string) =>
posts.filter(({ content, excerpt, title }) =>
[content, excerpt, title].some((field) =>
field?.toLowerCase().includes(term.toLowerCase())
)
);
/**
* Returns an filtered BlogPost list
*
* @param posts Posts to be handled
* @param slug Category Slug to be filter
*/
export const filterRelatedPosts = (
posts: BlogPost[],
slug: string[],
) =>
posts.filter(
({ categories }) => categories?.find((c) => slug.includes(c.slug)),
);
/**
* Returns an filtered and sorted BlogPost list
*
* @param posts Posts to be handled
* @param pageNumber Actual page number
* @param postsPerPage Number of posts per page
*/
export const slicePosts = (
posts: BlogPost[],
pageNumber: number,
postsPerPage: number,
) => {
const startIndex = (pageNumber - 1) * postsPerPage;
const endIndex = startIndex + postsPerPage;
return posts.slice(startIndex, endIndex);
};
/**
* A record without a slug has no route, so it can never be rendered: listing it
* only produces cards linking to the listing itself. Dropped here, before
* slicePosts, so `count` still yields `count` renderable posts.
*/
export const filterRoutablePosts = (posts: BlogPost[]) =>
// Records come straight from the CMS, so `slug` is only a string by
// convention: the typeof guard keeps a malformed one from throwing here and
// taking the whole listing down with it.
posts.filter(({ slug }) => typeof slug === "string" && slug.trim());
const filterPosts = (
allPosts: BlogPost[],
slug?: string | string[],
postSlugs?: string[],
term?: string,
): BlogPost[] => {
const posts = filterRoutablePosts(allPosts);
if (typeof slug === "string") {
const firstFilter = postSlugs && postSlugs.length > 0
? filterPostsBySlugs(posts, postSlugs)
: filterPostsByCategory(posts, slug);
const filteredByTerm = term
? filterPostsByTerm(firstFilter, term)
: firstFilter;
return filteredByTerm;
}
if (Array.isArray(slug)) {
return filterRelatedPosts(posts, slug);
}
return term ? filterPostsByTerm(posts, term) : posts;
};
/**
* Returns an filtered and sorted BlogPost list. It dont slice
*
* @param posts Posts to be handled
* @param sortBy Sort option (must be: "date_desc" | "date_asc" | "title_asc" | "title_desc")
* @param ctx AppContext
* @param slug Category slug or an array of slugs to be filtered
* @param postSlugs Specific slugs to be filtered
* @param term Term to be filtered
* @param excludePostSlug Slug to be excluded
*/
export default async function handlePosts(
posts: BlogPost[],
sortBy: SortBy,
ctx: AppContext,
slug?: string | string[],
postSlugs?: string[],
term?: string,
excludePostSlug?: string,
) {
const filteredPosts = filterPosts(posts, slug, postSlugs, term).filter(
({ slug: postSlug }) => postSlug !== excludePostSlug,
);
if (!filteredPosts || filteredPosts.length === 0) {
return null;
}
const sorted = await sortPosts(filteredPosts, sortBy, ctx);
return sorted;
}