Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

#365 created page with xml(rss) #432

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
3 changes: 3 additions & 0 deletions next-app/.gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -22,3 +22,6 @@ yarn-error.log*

# local env files
.env*.local

#RSS
/public/feed.xml
42 changes: 42 additions & 0 deletions next-app/api/index.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import path from 'path';
import fsp from 'fs/promises';
import fs from 'fs';

import matter from 'gray-matter';
import remarkGfm from 'remark-gfm';
import rehypePrism from '@mapbox/rehype-prism';
import { serialize } from 'next-mdx-remote/serialize';
import { Feed } from 'feed';
import findLastIndex from 'lodash.findlastindex';
import capitalize from 'lodash.capitalize';

Expand Down Expand Up @@ -93,3 +95,43 @@ export const findPost = async (name, locale) => {
content: compiledSource,
};
};

export const generateRssFeed = async (locale) => {
const posts = await getPublishedPosts(locale);
const postsToShow = posts.filter(({ hidden = false }) => !hidden);

const siteURL = 'http://localhost:3000';
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Кажется так быть не должно - https://github.com/Hexlet/hexletguides.github.io/blob/gh-pages/feed.xml#L8:

<link>https://guides.hexlet.io/</link>

const date = new Date();

const feed = new Feed({
title: "Hexlet Guides",
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Такие параметры лучше брать из конфига

description: "Полезные статьи и гайды для разработчиков",
id: siteURL,
link: siteURL,
language: locale,
image: `${siteURL}/favicon.ico`,
favicon: `${siteURL}/favicon.ico`,
updated: date, // today's date
feedLinks: {
rss2: `${siteURL}/feed.xml`,
},
author: 'Kirill Mokevnin',
});

postsToShow.forEach((post) => {
feed.addItem({
title: post.header,
id: post.sourceUrl,
link: post.sourceUrl,
description: post.summary,
content: post.content,
author: {
name: post.author,
},
// image: post.image,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Не используемый код лучше удалить

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Еще кажется, что дата публикации все же должна быть:

<pubDate>Fri, 10 Jun 2022 00:00:00 +0000</pubDate>

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Пост не содержит информацию о дате публикации. В каждом файле есть ключи title, subtitle, description, image и author. Или дату можно получить как-то ещё?

// date: new Date(post.date),
});
});

fs.writeFileSync("./public/feed.xml", feed.rss2());
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
fs.writeFileSync("./public/feed.xml", feed.rss2());
return fsp.writeFile("./public/feed.xml", feed.rss2());

};
49 changes: 49 additions & 0 deletions next-app/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions next-app/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
"@mapbox/rehype-prism": "^0.8.0",
"bootstrap": "^5.1.3",
"disqus-react": "^1.1.3",
"feed": "^4.2.2",
"file-loader": "^6.2.0",
"gray-matter": "^4.0.3",
"lodash.capitalize": "^4.2.1",
Expand Down
3 changes: 2 additions & 1 deletion next-app/pages/index.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { useTranslation } from 'next-i18next';
import { serverSideTranslations } from 'next-i18next/serverSideTranslations';

import { getPostsList } from '../api/index.js';
import { getPostsList, generateRssFeed } from '../api/index.js';
import DefaultLayout from '../components/DefaultLayout.jsx';
import HomePageInfo from '../components/HomePageInfo.jsx';

Expand All @@ -18,6 +18,7 @@ const Home = ({ posts }) => {
export const getStaticProps = async ({ locale }) => ({
props: {
posts: await getPostsList(locale),
...await generateRssFeed(locale),
Copy link
Contributor

@seth2810 seth2810 Sep 12, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Есть ощущение, что генерация должна выполняться не здесь, а в отдельной команде перед деплоем (см. как сделан sitemap)

@see

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@seth2810 Привет, я попытался сделать пребилд скрипт (“prebuild”: “node <путь к скрипту>”), но так как в package.json не указан “type”: ”module”, команда падает с ошибкой. Так как в скрипте используется код, который выполняется в рамках рантайма next.js, все функции (с зависимостями) переписать на CommonJS модули тоже не вышло. Попытки использовать расширение .mjs и флаги типа —experimental-modules так же не привели к успеху. Пожалуйста, подскажи, как можно решить эту проблему

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@Aleksandr-Bondarev предлагаю тебе запушить свой код, пусть и не рабочий, чтобы я мог смотреть предметно 😉

Copy link
Contributor

@seth2810 seth2810 Sep 18, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@Aleksandr-Bondarev учитывая, что будет необходимо генерировать фиды под разные локали, нашел другой способ позволяющий это сделать более привычным для next.js путем. Еще там выяснилось, что обычный feed нам не подходит, и лучше использовать turbo-rss. Завтра постараюсь прислать PR в твой репозиторий с правками. Так же переделаем заодно генерацию sitemap's, чтобы было единообразно 🤝

...(await serverSideTranslations(locale, ['common'])),
},
});
Expand Down