搜索
首页web前端js教程将多个博客 API 集成到 Astro 站点中:Dev.to 和 Hashnode

Integrando Múltiples APIs de Blog en un Sitio Astro: Dev.to y Hashnode

如果您像我一样,您可能会在多个博客平台上写作。就我而言,我使用 Dev.to 和 Hashnode 来接触不同的受众。但是,当您想在个人网站上显示所有帖子时会发生什么?今天我将向您展示如何将这两个 API 集成到我用 Astro 构建的产品组合中。

挑战

主要挑战是:

  1. 从两个不同的 API 获取消息
  2. 统一数据格式
  3. 按时间顺序排列
  4. 处理错误和速率限制
  5. 使用 TypeScript 进行安全输入

初始配置

首先,我们定义输入数据的接口:

interface BlogPost {
  title: string;
  brief: string;
  slug: string;
  dateAdded: string;
  rawDate: string;
  coverImage: string;
  url: string;
  source: string;
}

interface HashnodeEdge {
  node: {
    title: string;
    brief: string;
    slug: string;
    dateAdded: string;
    coverImage?: {
      url: string;
    };
    url: string;
  };
}

集成开发

Dev.to API 是 RESTful 并且相当简单。这是我的实现方式:

async function getDevToPosts() {
  try {
    const params = new URLSearchParams({
      username: 'tuUsuario',
      per_page: '20',
      state: 'all',
      sort: 'published_at',
      order: 'desc'
    });

    const headers = {
      'Accept': 'application/vnd.forem.api-v1+json'
    };

    // Agregar API key si está disponible
    if (import.meta.env.DEV_TO_API_KEY) {
      headers['api-key'] = import.meta.env.DEV_TO_API_KEY;
    }

    const response = await fetch(`https://dev.to/api/articles?${params}`, { headers });

    if (!response.ok) {
      throw new Error(`HTTP ${response.status}`);
    }

    const posts = await response.json();

    return posts.map((post: any) => ({
      title: post.title,
      brief: post.description,
      slug: post.slug,
      dateAdded: formatDate(post.published_timestamp),
      rawDate: post.published_timestamp,
      coverImage: post.cover_image || '/images/default-post.png',
      url: post.url,
      source: 'devto'
    }));
  } catch (error) {
    console.error('Error al obtener posts de Dev.to:', error);
    return [];
  }
}

集成哈希节点

Hashnode 使用 GraphQL,这需要稍微不同的方法:

async function getHashnodePosts() {
  try {
    const query = `
      query {
        publication(host: "tuBlog.hashnode.dev") {
          posts(first: 20) {
            edges {
              node {
                title
                brief
                slug
                dateAdded: publishedAt
                coverImage {
                  url
                }
                url
              }
            }
          }
        }
      }
    `;

    const response = await fetch('https://gql.hashnode.com', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ query })
    });

    const { data } = await response.json();

    return data.publication.posts.edges.map((edge: HashnodeEdge) => ({
      title: edge.node.title,
      brief: edge.node.brief,
      slug: edge.node.slug,
      dateAdded: formatDate(edge.node.dateAdded),
      rawDate: edge.node.dateAdded,
      coverImage: edge.node.coverImage?.url || '/images/default-post.png',
      url: edge.node.url,
      source: 'hashnode'
    }));
  } catch (error) {
    console.error('Error al obtener posts de Hashnode:', error);
    return [];
  }
}

合并结果

组合和排序帖子时会发生神奇的事情:

const hashnodePosts = await getHashnodePosts();
const devtoPosts = await getDevToPosts();

const allBlogPosts = [...hashnodePosts, ...devtoPosts]
  .sort((a, b) => new Date(b.rawDate).getTime() - new Date(a.rawDate).getTime());

错误处理和速率限制

为了处理速率限制和错误,我实施了以下策略:

客户端缓存:

const CACHE_DURATION = 5 * 60 * 1000; // 5 minutos
let postsCache = {
  data: null,
  timestamp: 0
};

async function getAllPosts() {
  const now = Date.now();
  if (postsCache.data && (now - postsCache.timestamp) 



<h3>
  
  
  使用指数退避重试:
</h3>



<pre class="brush:php;toolbar:false">async function fetchWithRetry(url: string, options: any, retries = 3) {
  for (let i = 0; i  setTimeout(resolve, parseInt(retryAfter) * 1000));
        continue;
      }
      return response;
    } catch (error) {
      if (i === retries - 1) throw error;
      await new Promise(resolve => setTimeout(resolve, Math.pow(2, i) * 1000));
    }
  }
}

以 Astro 渲染

最后,我们在 Astro 组件中渲染帖子:

---
const allBlogPosts = 等待 getAllPosts();
---

<div>



<p>这种集成使我们能够:</p>

<ul>
<li>维护我们帖子的单一事实来源</li>
<li>显示来自多个平台的内容</li>
<li>优雅地处理错误</li>
<li>维护输入的安全代码</li>
</ul>

<p>完整的代码可以在我的 GitHub 上找到。</p>

<p>您是否将其他博客平台集成到您的网站中?在评论中分享您的经验! ?</p>

<h2>
  
  
  webdev #astro #typescript #api
</h2>


          </div>

            
        

以上是将多个博客 API 集成到 Astro 站点中:Dev.to 和 Hashnode的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
JavaScript数据类型:浏览器和nodejs之间是否有区别?JavaScript数据类型:浏览器和nodejs之间是否有区别?May 14, 2025 am 12:15 AM

JavaScript核心数据类型在浏览器和Node.js中一致,但处理方式和额外类型有所不同。1)全局对象在浏览器中为window,在Node.js中为global。2)Node.js独有Buffer对象,用于处理二进制数据。3)性能和时间处理在两者间也有差异,需根据环境调整代码。

JavaScript评论:使用//和 / * * / * / * /JavaScript评论:使用//和 / * * / * / * /May 13, 2025 pm 03:49 PM

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python vs. JavaScript:开发人员的比较分析Python vs. JavaScript:开发人员的比较分析May 09, 2025 am 12:22 AM

Python和JavaScript的主要区别在于类型系统和应用场景。1.Python使用动态类型,适合科学计算和数据分析。2.JavaScript采用弱类型,广泛用于前端和全栈开发。两者在异步编程和性能优化上各有优势,选择时应根据项目需求决定。

Python vs. JavaScript:选择合适的工具Python vs. JavaScript:选择合适的工具May 08, 2025 am 12:10 AM

选择Python还是JavaScript取决于项目类型:1)数据科学和自动化任务选择Python;2)前端和全栈开发选择JavaScript。Python因其在数据处理和自动化方面的强大库而备受青睐,而JavaScript则因其在网页交互和全栈开发中的优势而不可或缺。

Python和JavaScript:了解每个的优势Python和JavaScript:了解每个的优势May 06, 2025 am 12:15 AM

Python和JavaScript各有优势,选择取决于项目需求和个人偏好。1.Python易学,语法简洁,适用于数据科学和后端开发,但执行速度较慢。2.JavaScript在前端开发中无处不在,异步编程能力强,Node.js使其适用于全栈开发,但语法可能复杂且易出错。

JavaScript的核心:它是在C还是C上构建的?JavaScript的核心:它是在C还是C上构建的?May 05, 2025 am 12:07 AM

javascriptisnotbuiltoncorc; saninterpretedlanguagethatrunsonenginesoftenwritteninc.1)javascriptwasdesignedAsalightweight,解释edganguageforwebbrowsers.2)Enginesevolvedfromsimpleterterterpretpreterterterpretertestojitcompilerers,典型地提示。

JavaScript应用程序:从前端到后端JavaScript应用程序:从前端到后端May 04, 2025 am 12:12 AM

JavaScript可用于前端和后端开发。前端通过DOM操作增强用户体验,后端通过Node.js处理服务器任务。1.前端示例:改变网页文本内容。2.后端示例:创建Node.js服务器。

Python vs. JavaScript:您应该学到哪种语言?Python vs. JavaScript:您应该学到哪种语言?May 03, 2025 am 12:10 AM

选择Python还是JavaScript应基于职业发展、学习曲线和生态系统:1)职业发展:Python适合数据科学和后端开发,JavaScript适合前端和全栈开发。2)学习曲线:Python语法简洁,适合初学者;JavaScript语法灵活。3)生态系统:Python有丰富的科学计算库,JavaScript有强大的前端框架。

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SecLists

SecLists

SecLists是最终安全测试人员的伙伴。它是一个包含各种类型列表的集合,这些列表在安全评估过程中经常使用,都在一个地方。SecLists通过方便地提供安全测试人员可能需要的所有列表,帮助提高安全测试的效率和生产力。列表类型包括用户名、密码、URL、模糊测试有效载荷、敏感数据模式、Web shell等等。测试人员只需将此存储库拉到新的测试机上,他就可以访问到所需的每种类型的列表。

螳螂BT

螳螂BT

Mantis是一个易于部署的基于Web的缺陷跟踪工具,用于帮助产品缺陷跟踪。它需要PHP、MySQL和一个Web服务器。请查看我们的演示和托管服务。

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

功能强大的PHP集成开发环境

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用