Improved logic to check whether more older posts are available

This commit is contained in:
Max Nuding 2023-04-05 20:41:36 +02:00
parent a3fb47a329
commit fee1475779
Signed by: phlaym
GPG Key ID: A06651BAB6777237

View File

@ -13,13 +13,22 @@ let interval: NodeJS.Timer | null = null;
let moreOlderPostsAvailable = true;
let loadingOlderPosts = false;
async function fetchPosts(filter: { since?: string, before?: string }): Promise<Post[]> {
const params = new URLSearchParams();
if (filter?.since !== undefined) {
params.set('since', filter.since);
interface FetchOptions {
since?: string,
before?: string,
count?: number
}
if (filter?.before !== undefined) {
params.set('before', filter.before);
async function fetchPosts(options: FetchOptions): Promise<Post[]> {
const params = new URLSearchParams();
if (options?.since !== undefined) {
params.set('since', options.since);
}
if (options?.before !== undefined) {
params.set('before', options.before);
}
if (options?.count !== undefined) {
params.set('count', options.count.toFixed(0));
}
const response = await fetch(`/api/posts?${params}`);
@ -33,7 +42,7 @@ function filterDuplicates(posts: Post[]): Post[] {
}
function refresh() {
let filter = {};
let filter: FetchOptions = {};
if (data.posts.length > 0) {
filter = { since: data.posts[0].created_at };
}
@ -72,9 +81,9 @@ onMount(async () => {
function loadOlderPosts() {
loadingOlderPosts = true;
let filter = {};
const filter: FetchOptions = { count: 20 };
if (data.posts.length > 0) {
filter = { before: data.posts[data.posts.length - 1].created_at };
filter.before = data.posts[data.posts.length - 1].created_at;
}
@ -83,7 +92,8 @@ function loadOlderPosts() {
// Append old posts, filter dupes
// There shouldn't be any duplicates, but better be safe than sorry
data.posts = filterDuplicates(data.posts.concat(resp));
moreOlderPostsAvailable = true;
// If we got less than we expected, there are no older posts available
moreOlderPostsAvailable = resp.length < (filter.count ?? 20);
} else {
moreOlderPostsAvailable = false;
}