Interrogare i contenuti

In questa pagina

EmDash fornisce funzioni di query per recuperare contenuti in pagine e componenti Astro. Seguono lo schema delle live content collections di Astro e restituiscono risultati strutturati con gestione degli errori.

Funzioni di query

EmDash esporta due funzioni principali:

FunzioneScopoRestituisce
getEmDashCollectionTutte le voci di un tipo di contenuto{ entries, error }
getEmDashEntryUna singola voce per ID o slug{ entry, error, isPreview }

Import da emdash:

import { getEmDashCollection, getEmDashEntry } from "emdash";

Ottenere tutte le voci

Usa getEmDashCollection per caricare tutte le voci di un tipo di contenuto:

---
import { getEmDashCollection } from "emdash";

const { entries: posts, error } = await getEmDashCollection("posts");

if (error) {
  console.error("Failed to load posts:", error);
}
---

<ul>
  {posts.map((post) => (
    <li>{post.data.title}</li>
  ))}
</ul>

Filtrare per locale

Con i18n abilitata, filtra per locale:

// Articoli in francese
const { entries: frenchPosts } = await getEmDashCollection("posts", {
	locale: "fr",
	status: "published",
});

// Locale corrente della richiesta
const { entries: localizedPosts } = await getEmDashCollection("posts", {
	locale: Astro.currentLocale,
	status: "published",
});

Per una singola voce, passa locale come terzo argomento:

const { entry: post } = await getEmDashEntry("posts", "my-post", {
	locale: Astro.currentLocale,
});

Senza locale si usa la locale della richiesta. Se manca la traduzione, vale la catena di fallback.

Filtrare per stato

Solo pubblicato o solo bozza:

const { entries: published } = await getEmDashCollection("posts", {
	status: "published",
});

const { entries: drafts } = await getEmDashCollection("posts", {
	status: "draft",
});

Limitare i risultati

const { entries: recentPosts } = await getEmDashCollection("posts", {
	status: "published",
	limit: 5,
});

Filtrare per tassonomia

Per categoria, tag o termine personalizzato:

const { entries: newsPosts } = await getEmDashCollection("posts", {
	status: "published",
	where: { category: "news" },
});

const { entries: jsPosts } = await getEmDashCollection("posts", {
	status: "published",
	where: { tag: "javascript" },
});

const { entries: featuredNews } = await getEmDashCollection("posts", {
	status: "published",
	where: { category: ["news", "featured"] },
});

Il filtro where usa logica OR con più valori per la stessa tassonomia.

Gestione errori

Controlla sempre gli errori quando serve affidabilità:

const { entries: posts, error } = await getEmDashCollection("posts");

if (error) {
	console.error("Failed to load posts:", error);
	return new Response("Server error", { status: 500 });
}

Ottenere una singola voce

getEmDashEntry carica una voce per ID o slug:

---
import { getEmDashEntry } from "emdash";
import { PortableText } from "emdash/ui";

const { slug } = Astro.params;
const { entry: post, error } = await getEmDashEntry("posts", slug);

if (error) {
  return new Response("Server error", { status: 500 });
}

if (!post) {
  return Astro.redirect("/404");
}
---

<article>
  <h1>{post.data.title}</h1>
  <PortableText value={post.data.content} />
</article>

Tipo di ritorno

interface EntryResult<T> {
	entry: ContentEntry<T> | null;
	error?: Error;
	isPreview: boolean;
}

interface ContentEntry<T> {
	id: string;
	data: T;
	edit: EditProxy;
}

Modalità anteprima

EmDash gestisce l’anteprima tramite middleware. Con _preview valido, le query servono la bozza senza parametri extra:

---
import { getEmDashEntry } from "emdash";

const { slug } = Astro.params;

const { entry, isPreview, error } = await getEmDashEntry("posts", slug);

if (error) {
  return new Response("Server error", { status: 500 });
}

if (!entry) {
  return Astro.redirect("/404");
}
---

{isPreview && (
  <div class="preview-banner">
    Anteprima. Questo contenuto non è pubblicato.
  </div>
)}

<article>
  <h1>{entry.data.title}</h1>
  <PortableText value={entry.data.content} />
</article>

Editing visivo

<article {...entry.edit}>
  <h1 {...entry.edit.title}>{entry.data.title}</h1>
  <div {...entry.edit.content}>
    <PortableText value={entry.data.content} />
  </div>
</article>

Ordinamento

getEmDashCollection non garantisce l’ordine. Ordina nel template:

const { entries: posts } = await getEmDashCollection("posts", {
	status: "published",
});

const sorted = posts.sort(
	(a, b) => (b.data.publishedAt?.getTime() ?? 0) - (a.data.publishedAt?.getTime() ?? 0),
);
posts.sort((a, b) => a.data.title.localeCompare(b.data.title));
posts.sort((a, b) => (a.data.order ?? 0) - (b.data.order ?? 0));
posts.sort(() => Math.random() - 0.5);

TypeScript

npx emdash types
import { getEmDashCollection, getEmDashEntry } from "emdash";
import type { Post } from "../.emdash/types";

const { entries: posts } = await getEmDashCollection<Post>("posts");
const { entry: post } = await getEmDashEntry<Post>("posts", "my-post");

Statico vs server

Statico

---
import { getEmDashCollection, getEmDashEntry } from "emdash";

export async function getStaticPaths() {
  const { entries: posts } = await getEmDashCollection("posts", {
    status: "published",
  });

  return posts.map((post) => ({
    params: { slug: post.data.slug },
  }));
}

const { slug } = Astro.params;
const { entry: post } = await getEmDashEntry("posts", slug);
---

Rendering lato server

---
export const prerender = false;

import { getEmDashEntry } from "emdash";

const { slug } = Astro.params;
const { entry: post, error } = await getEmDashEntry("posts", slug);

if (error) {
  return new Response("Server error", { status: 500 });
}

if (!post) {
  return new Response(null, { status: 404 });
}
---

Prestazioni

Cache

---
const { entries: posts } = await getEmDashCollection("posts", {
  status: "published",
});

Astro.response.headers.set("Cache-Control", "public, max-age=300");
---

Evitare query duplicate

---
import { getEmDashCollection } from "emdash";
import PostList from "../components/PostList.astro";
import Sidebar from "../components/Sidebar.astro";

const { entries: posts } = await getEmDashCollection("posts", {
  status: "published",
});

const featured = posts.filter((p) => p.data.featured);
const recent = posts.slice(0, 5);
---

<PostList posts={featured} />
<Sidebar posts={recent} />

Passi successivi