From bf1b29083cb2cbe99c3ab12dd7a1dd8fa749b8e6 Mon Sep 17 00:00:00 2001 From: Arild Matsson Date: Wed, 24 Apr 2024 16:17:25 +0200 Subject: [PATCH] Skip old news --- src/home/news.service.ts | 9 +++++---- src/util.test.ts | 14 ++++++++++++++ src/util.ts | 12 ++++++++++++ 3 files changed, 31 insertions(+), 4 deletions(-) diff --git a/src/home/news.service.ts b/src/home/news.service.ts index 4ececdc..c1407c1 100644 --- a/src/home/news.service.ts +++ b/src/home/news.service.ts @@ -1,6 +1,6 @@ const Yaml = import("js-yaml").then((m) => m.default); import once from "lodash/once"; -import { retry } from "@/util"; +import { addDays, retry } from "@/util"; import type { ByLang } from "@/util.types"; const NEWS_URL: string = import.meta.env.VITE_NEWS_URL; @@ -40,10 +40,11 @@ export const fetchAllNews = once(async (): Promise => { * @throws Fetch or parse errors */ export async function fetchNews(filterFeatured?: boolean): Promise { - // Get news and skip items that have expired - // TODO Also skip items older than 6 months + const now = new Date(); let items = (await fetchAllNews()).filter( - (item) => !item.expires || item.expires > new Date(), + (item) => + (!item.expires || item.expires > now) && // Skip expired items + item.created > addDays(now, -365 / 2), // Skip items older than 6 months ); // Filter by the "featured" tag if specified diff --git a/src/util.test.ts b/src/util.test.ts index d863de0..8f33ed3 100644 --- a/src/util.test.ts +++ b/src/util.test.ts @@ -1,5 +1,6 @@ import { describe, expect, test } from "vitest"; import { + addDays, enarray, ensureExtension, formatDate, @@ -15,6 +16,19 @@ import { unarray, } from "@/util"; +describe("addDays", () => { + const d = new Date("24 April 2024 15:50 (CEST)"); + test("across a month", () => { + expect(addDays(d, 10)).toEqual(new Date("4 May 2024 15:50 (CEST)")); + expect(addDays(d, -24)).toEqual(new Date("31 March 2024 15:50 (CEST)")); + }); + test("across DST", () => { + // Notice the hour is different + expect(addDays(d, 200)).toEqual(new Date("10 November 2024 14:50 (CET)")); + expect(addDays(d, -25)).toEqual(new Date("30 March 2024 14:50 (CET)")); + }); +}); + describe("enarray", () => { test("leaves array unchanged", () => { expect(enarray([1, 2, 3])).toStrictEqual([1, 2, 3]); diff --git a/src/util.ts b/src/util.ts index ad9ee71..e544dc3 100644 --- a/src/util.ts +++ b/src/util.ts @@ -1,6 +1,18 @@ import clone from "lodash/clone"; import round from "lodash/round"; +/** The number of milliseconds in a full day. */ +const DAY_MS = 24 * 60 * 60 * 1000; + +/** + * Add or subtract a number of days to a date + * + * Works with 24-hour cycles, so the hour (and possibly date) will change across DST changes. + **/ +export function addDays(date: Date, days: number) { + return new Date(date.getTime() + days * DAY_MS); +} + export const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms)); /** Trigger a file download in the browser by adding a temporary link and click it */