summaryrefslogtreecommitdiff
path: root/src/lib/newsUtils.ts
blob: bffc7d61c2c3f4672d6bae5fd2cba82926dfb6ee (plain)
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
import locales from '$i18n/locales';
import type Locale from '$types/Locale';
import { getCollection, type CollectionEntry } 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(prev, curr) ? curr : prev), someNewsItem);
}

export function getLocale(newsItem: CollectionEntry<'news'>) {
  const srcPath = newsItem.id;
  return srcPath.slice(0, srcPath.indexOf('/'));
}

export function getHref(newsItem: CollectionEntry<'news'>) {
  const locale = getLocale(newsItem);
  return `/${locale}/news/${getSlug(newsItem)}`;
}

export function getSlug(newsItem: CollectionEntry<'news'>) {
  const toLowerCase = (s: string) => s.toLowerCase();
  const matchLocales = new RegExp(`(${locales.map(toLowerCase).join('|')})/`);
  return newsItem.slug.replace(matchLocales, '');
}

export function isNewsItemInLocale(newsItem: CollectionEntry<'news'>, locale: Locale) {
  const newsItemLocale = getLocale(newsItem);
  return newsItemLocale === locale;
}

export function isBefore(item1: CollectionEntry<'news'>, item2: CollectionEntry<'news'>) {
  const date1 = getDate(item1);
  const date2 = getDate(item2);
  if (!date2) {
    return false;
  }
  if (!date1) {
    return true;
  }
  return date1.valueOf() < date2.valueOf();
}

export function getDate(newsItem: CollectionEntry<'news'>) {
  const matchDate = new RegExp(`(${locales.join('|')})/(\\d\\d\\d\\d-\\d\\d-\\d\\d)`);
  const date = newsItem.id.match(matchDate)?.[2];
  return date ? new Date(date) : null;
}