//tips
npm trendsを確認し、導入可能なパッケージを探す方法や秒でgithubに公開できるようにすることを教わった。仕事が早くてビビった。さすがプロだった。このレベルをまずは目指す。
https://www.npmtrends.com/
https://github.com/saurabhnemade/react-twitter-embed#readme
//smart contract
調べていくとMediumは他のアプリでブログ内容を取得できるようなapiは提供していないよう。
The API is write-only and is not intended to retrieve posts (Medium staff told me)
なので代わりにRSS feedを使う方法もあると紹介されていた。
You can simply use the RSS feed as such:
https://medium.com/feed/@your_profile
You can simply get the RSS feed via GET, then if you need it in JSON format just use a NPM module like rss-to-json and you're good to go.
rss-to-jsonとは、rss のフォーマットである xmlをJavaScript で使おうと思うと不便なので、これをjsonに変換してくれるサービスとのこと。
var endpoint = "https://api.rss2json.com/v1/api.json";
var feed_url = "https://zenn.dev/topics/rabee/feed";
// rss feed を取得
var res = await fetch(`https://api.rss2json.com/v1/api.json?rss_url=${feed_url}`);
// text を json 化
var data = await res.json();
参考:
https://zenn.dev/phi/articles/js-fetch-rss-feed-as-json
https://medium.com/swlh/how-to-render-medium-blog-posts-on-your-website-f14ef11dd20
mediumの場合のfeedはhttps://medium.com/feed/@yourhandleのようになるそうなので、
自身のアカウントで簡単なページを作成。
https://medium.com/feed/@Nakithemagic
その後に実際に入ってみるときちんとXML形式での表示が確認できた。
下記をindexの中に追加。
async function handleOnMediumSubmit(e) {
e.preventDefault();
const endpoint = "https://api.rss2json.com/v1/api.json";
const feed_url = "https://medium.com/feed/@Nakithemagic";
// rss feed を取得
var res = await fetch(`https://api.rss2json.com/v1/api.json?rss_url=${feed_url}`);
// text を json 化
var data = await res.json();
data.items.forEach(item => {
var $post = document.createElement('div');
$post.innerHTML = `
<h3><a href='${item.title}'>${item.title}</a></h3>
<p>${item.description}</p>
`;
$post.classList.add('post');
$posts.appendChild($post);
});
}
$postが定義されていませんなどのエラーが出る。きちんとnext.jsに合う形に直してあげる。
async function handleOnMediumSubmit(e) {
e.preventDefault();
const endpoint = "https://api.rss2json.com/v1/api.json";
const feed_url = "https://medium.com/feed/@Nakithemagic";
// rss feed を取得
var res = await fetch(`https://api.rss2json.com/v1/api.json?rss_url=${feed_url}`);
// text を json 化
var results = await res.json();
console.log("medium");
console.log(results);
setMedium(results.items);
}
これで無事にfeedからの取得ができた。
{mymedium && (
<ul>
{ mymedium.map(({ id,author, title }) => {
return (
<li key={id}>
<p>{ author }</p>
<p>{ title } </p>
</li>
);
})}
</ul>
)}
items: Array(1)
0: {title: 'Hi Medium', pubDate: '2022-02-26 03:51:30', …
ただ、この0の引き取り方がわからず。{id}ではkeyは設定されていませんと出るので、これではないよう。
配列の中の連想配列の処理なので、確認。
よく考えると認証させて情報を得ない方がいいのではないか…他の人のページも見るので、自身のページの設定の際のみルートを取得するなどにした方がいいかもしれない。成り代わりなどの問題があるので、そちらの対処をできるようにしておけば良い。認証制度をこちらに使うなど。
ここはmozillaでmap()を確認する必要があり、引数にindexが取れることを教えてもらった。
ただ、それでもエラーが出ているので現在確認中。
{mymedium && (
<ul>
{ mymedium.map((item,index) => {
return (
<li key={index}>
<p>{ item.author }</p>
<p>{ item.title } </p>
</li>
);
})}