diff options
| author | Joe Carstairs <jcarstairs@scottlogic.com> | 2023-08-15 19:15:27 +0100 |
|---|---|---|
| committer | Joe Carstairs <jcarstairs@scottlogic.com> | 2023-08-15 19:15:27 +0100 |
| commit | 53f29bac911b13b2bef0125de22773bf26ce5a90 (patch) | |
| tree | e4dad6d88e2fe4c4eda8ff286db50d9a6f561242 /src/lib | |
| parent | 8b009f0ea6ea9d181ba8d0e6549c25645aa697c4 (diff) | |
Adds homepage
Diffstat (limited to 'src/lib')
| -rw-r--r-- | src/lib/newsUtils.ts | 35 |
1 files changed, 35 insertions, 0 deletions
diff --git a/src/lib/newsUtils.ts b/src/lib/newsUtils.ts new file mode 100644 index 0000000..ededb52 --- /dev/null +++ b/src/lib/newsUtils.ts @@ -0,0 +1,35 @@ +import type Locale from '$types/Locale'; +import { CollectionEntry, getCollection } from 'astro:content'; + +export async function getMostRecentNewsItem(locale: Locale) { + const allNews = await getCollection('news'); + const allNewsInLocale = allNews.filter((item) => isNewsItemInLocale(item, locale)); + const someNewsItem = allNewsInLocale.at(0); + if (!someNewsItem) { + return null; + } + return allNewsInLocale.reduce((prev, curr) => (isBefore(curr, prev) ? curr : prev), someNewsItem); +} + +export function isNewsItemInLocale(newsItem: CollectionEntry<'news'>, locale: Locale) { + const srcPath = newsItem.id; + const newsItemLocale = srcPath.slice(0, srcPath.indexOf('/')); + return newsItemLocale === locale; +} + +function isBefore(item1: CollectionEntry<'news'>, item2: CollectionEntry<'news'>) { + const date1 = dateOf(item1); + const date2 = dateOf(item2); + if (!date2) { + return false; + } + if (!date1) { + return true; + } + return date1.valueOf() < date2.valueOf(); +} + +function dateOf(newsItem: CollectionEntry<'news'>) { + const match = newsItem.id.match(/(?<=(en-GB|sco))\/(\d\d\d\d-\d\d-\d\d)/)?.[2]; + return match ? new Date(match) : null; +} |
