在 Astro 开发我的个人作品集期间,我遇到了一个有趣的挑战:如何有效地集成我的 Dev.to 和 Hashnode 帖子,而不必每次发帖时都重建网站新内容?
问题一开始似乎很简单:在一个页面上显示我来自两个平台的所有帖子。然而,我遇到了一些挑战:
我在 Astro 中创建了一个无服务器端点,它结合了两个平台的帖子:
export const GET: APIRoute = async () => { const [hashnodePosts, devtoPosts] = await Promise.all([ getHashnodePosts(), getDevToPosts() ]); const allPosts = [...hashnodePosts, ...devtoPosts] .sort((a, b) => new Date(b.rawDate).getTime() - new Date(a.rawDate).getTime() ); return new Response(JSON.stringify(allPosts), { headers: { 'Content-Type': 'application/json', 'Cache-Control': 'no-store, no-cache, must-revalidate' } }); };
关键是请求尽可能多的帖子数:
// Para Dev.to const params = new URLSearchParams({ username: 'goaqidev', per_page: '1000', // Máximo número de posts state: 'published' }); // Para Hashnode const query = ` query { publication(host: "goaqidev.hashnode.dev") { posts(first: 1000) { // Máximo número de posts edges { node { title brief // ...otros campos } } } } } `;
为了确保内容新鲜,我实施了反缓存策略:
const timestamp = new Date().getTime(); const response = await fetch(`/api/posts.json?_=${timestamp}`, { headers: { 'Cache-Control': 'no-cache', 'Pragma': 'no-cache' } });
为了保持界面最新,我创建了一个 React 组件来处理加载和更新帖子:
import { useState, useEffect } from 'react'; function BlogPosts() { const [posts, setPosts] = useState([]); const [loading, setLoading] = useState(true); useEffect(() => { const fetchPosts = async () => { try { const timestamp = new Date().getTime(); const response = await fetch(`/api/posts.json?_=${timestamp}`); const data = await response.json(); setPosts(data); } catch (error) { console.error('Error fetching posts:', error); } finally { setLoading(false); } }; fetchPosts(); // Actualizar cada 5 minutos const interval = setInterval(fetchPosts, 5 * 60 * 1000); return () => clearInterval(interval); }, []); if (loading) return <div>Cargando posts...</div>; return ( <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4"> {posts.map(post => ( <article key={post.id} className="card"> <h2>{post.title}</h2> <p>{post.brief}</p> <a href={post.url}>Leer más</a> </article> ))} </div> ); }
我实现了一个强大的错误处理系统:
async function fetchPosts() { try { const response = await fetch('/api/posts.json'); if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } const posts = await response.json(); return posts; } catch (error) { console.error('Error fetching posts:', error); // Intentar cargar desde caché local si está disponible const cachedPosts = localStorage.getItem('blog_posts'); return cachedPosts ? JSON.parse(cachedPosts) : []; } }
为了进一步提高性能,我实施了:
// Guardar posts en localStorage localStorage.setItem('blog_posts', JSON.stringify(posts)); // Cargar posts desde localStorage mientras se actualiza const cachedPosts = localStorage.getItem('blog_posts'); if (cachedPosts) { setPosts(JSON.parse(cachedPosts)); }
function PostImage({ src, alt }) { return ( <img loading="lazy" src={src} alt={alt} className="w-full h-48 object-cover" /> ); }
该解决方案已被证明是稳健且高效的,使我能够:
我计划实施:
以上是优化博客 API 集成:Dev.to 和 Hashnode 的经验教训的详细内容。更多信息请关注PHP中文网其他相关文章!