summaryrefslogtreecommitdiff
path: root/src/app/(main)/rss.xml/route.ts
blob: 35079484100a817f4c632cd76c7f95d2f7e1d604 (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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import { description, title } from '@/app/(main)/layout.config';
import { owner } from '@/app/(main)/layout.config';
import { baseUrl } from '@/lib/constants';
import { getPublishedPosts } from '@/lib/payload-posts';
import { Feed } from 'feed';

export const dynamic = 'force-dynamic';

const escapeForXML = (str: string) => {
  return str
    .replace(/&/g, '&')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&apos;');
};

export const GET = async () => {
  const feed = await createFeed();

  return new Response(feed.atom1(), {
    headers: {
      'Content-Type': 'application/xml',
    },
  });
};

async function createFeed(): Promise<Feed> {
  const feed = new Feed({
    title,
    description,
    id: baseUrl.href,
    language: 'en',
    copyright: `All rights reserved ${new Date().getFullYear()}, ${owner}`,
    image: new URL('/banner.png', baseUrl).href,
    favicon: new URL('/favicon.ico', baseUrl).href,
    link: baseUrl.href,
    feed: new URL('/api/rss.xml', baseUrl).href,
    updated: new Date(),
  });

  const { posts } = await getPublishedPosts({ limit: 1000 });

  for (const post of posts) {
    feed.addItem({
      title: post.title,
      description: post.description,
      link: new URL(post.url, baseUrl).href,
      image: post.image
        ? {
            title: post.title,
            type: 'image/png',
            url: escapeForXML(new URL(post.image, baseUrl.href).href),
          }
        : undefined,
      date: post.date,
      author: [
        {
          name: post.author,
        },
      ],
    });
  }

  return feed;
}