Logo

dev-resources.site

for different kinds of informations.

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

Published at
12/6/2024
Categories
webdev
astro
javascript
api
Author
goaqidev
Categories
4 categories in total
webdev
open
astro
open
javascript
open
api
open
Author
8 person written this
goaqidev
open
Integrando Múltiples APIs de Blog en un Sitio Astro: Dev.to y Hashnode

Si eres como yo, probablemente escribas en varias plataformas de blogging. En mi caso, uso tanto Dev.to como Hashnode para llegar a diferentes audiencias. Pero, ¿qué pasa cuando quieres mostrar todos tus posts en tu sitio personal? Hoy te mostraré cómo integré ambas APIs en mi portfolio construido con Astro.

El Desafío

El principal reto era:

  1. Obtener posts de dos APIs diferentes
  2. Unificar el formato de los datos
  3. Ordenarlos cronológicamente
  4. Manejar errores y rate limiting
  5. Tipado seguro con TypeScript

Configuración Inicial

Primero, definimos las interfaces para tipar nuestros datos:

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;
  };
}
Enter fullscreen mode Exit fullscreen mode

Integrando Dev.to

La API de Dev.to es RESTful y bastante directa. Aquí está cómo la implementé:

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 [];
  }
}
Enter fullscreen mode Exit fullscreen mode

Integrando Hashnode

Hashnode usa GraphQL, lo que requiere un enfoque ligeramente diferente:

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 [];
  }
}
Enter fullscreen mode Exit fullscreen mode

Combinando los Resultados

La magia ocurre al combinar y ordenar los posts:

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());
Enter fullscreen mode Exit fullscreen mode

Manejo de Errores y Rate Limiting

Para manejar el rate limiting y errores, implementé estas estrategias:

Caché del lado del cliente:

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) < CACHE_DURATION) {
    return postsCache.data;
  }

  // Obtener y combinar posts...

  postsCache = {
    data: allBlogPosts,
    timestamp: now
  };
  return allBlogPosts;
}
Enter fullscreen mode Exit fullscreen mode

Reintentos con backoff exponencial:

async function fetchWithRetry(url: string, options: any, retries = 3) {
  for (let i = 0; i < retries; i++) {
    try {
      const response = await fetch(url, options);
      if (response.status === 429) { // Rate limit
        const retryAfter = response.headers.get('Retry-After') || '60';
        await new Promise(resolve => 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));
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

Renderizado en Astro

Finalmente, renderizamos los posts en nuestro componente Astro:

---
const allBlogPosts = await getAllPosts();
---

<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
  {allBlogPosts.map((post) => (
    <article class="card">
      <img src={post.coverImage} alt={post.title} />
      <div class="p-4">
        <span class={`badge ${post.source}`}>
          {post.source === 'devto' ? 'Dev.to' : 'Hashnode'}
        </span>
        <h2>{post.title}</h2>
        <p>{post.brief}</p>
        <a href={post.url}>Leer más</a>
      </div>
    </article>
  ))}
</div>
Enter fullscreen mode Exit fullscreen mode

Esta integración nos permite:

  • Mantener una única fuente de verdad para nuestros posts
  • Mostrar contenido de múltiples plataformas
  • Manejar errores de manera elegante
  • Mantener un código tipado y seguro

El código completo está disponible en mi GitHub.

¿Has integrado otras plataformas de blogging en tu sitio? ¡Comparte tus experiencias en los comentarios! 👇

webdev #astro #typescript #api

astro Article's
30 articles in total
Favicon
Transforming Starlight into PDF: experience and insights
Favicon
Dynamic Routes in Astro (+load parameters from JSON)
Favicon
Import JSON Data in Astro (with Typescript)
Favicon
Use LateX in Astro.js for Markdown Rendering
Favicon
From Legacy to Lightning: Modernizing an Astro App with Daytona
Favicon
Having a Good Ol' RSS Feed in Astro
Favicon
A Date with Daytona: Exploring AstroJS and Sanity CMS
Favicon
Roast my portfolio
Favicon
SvelteKit VS Astro. laidback side by side
Favicon
✍️ Cross-Posting Astro Blog Posts to BlueSky Using GPT-4 🧠
Favicon
The best CMS for Astro: How to choose CMS for Astro projects
Favicon
Integrando Múltiples APIs de Blog en un Sitio Astro: Dev.to y Hashnode
Favicon
Construyendo un Portfolio Moderno con Astro y Tailwind CSS
Favicon
Hybrid Rendering Architecture using Astro and Go Fiber
Favicon
The Single Quote Curse: When AI Mistook an MDX Front Matter Issue for a YAML Bug
Favicon
First impressions of Astro: what I liked and disliked
Favicon
Mysterious Display in Astro: Unraveling the Secrets of the Development Environment
Favicon
Astro v5 Blog starter
Favicon
Letting the product shape the infrastructure
Favicon
Using Angular Inside of Astro
Favicon
AstroJS 5.1: Integra contenido de Dev.to de manera sencilla
Favicon
Less is More: The Case Against Feature-Bloated CMS
Favicon
Add content to your site: Markdown 📝
Favicon
Learn how to create an interactive pricing table with Astro JS, Tailwind CSS and Alpine.js
Favicon
So I created Linktree alternative...
Favicon
Debugging failed builds with Netlify
Favicon
API Keys y Variables de Entorno en Astro: Guía Completa de Seguridad
Favicon
Fighting with Redirects: A Journey of Astro Site Migration
Favicon
Why I Used Astro, Tailwind, and Qwik to Build My Personal Website
Favicon
Creating a Custom Astro Integration: Auto-Publishing to Hashnode

Featured ones: