feature: intergrated directus for posts

This commit is contained in:
libertyoms
2025-04-26 19:27:16 +02:00
parent 08965c3830
commit 809f5c6ff7
11 changed files with 530 additions and 95 deletions

8
lib/query/home.ts Normal file
View File

@ -0,0 +1,8 @@
import { readItems } from "@directus/sdk";
import { directus } from "../directus";
import { HeroSection } from "@/types";
export async function getHome() {
// Assuming '1' is the primary key for the singleton "home" item
return directus.request(readItems("home")) as unknown as HeroSection;
}

66
lib/query/post.ts Normal file
View File

@ -0,0 +1,66 @@
import { directus } from "@/lib/directus";
import { ItemsQuery, Post } from "@/types";
import { readItem, readItems } from "@directus/sdk";
// Construct base URL for assets from environment variable
const assetsUrl = `${process.env.DIRECTUS_API_ENDPOINT}/assets/`;
function getFullImageUrl(imageId: string | null | undefined): string | null {
if (!imageId || !assetsUrl) {
return null;
}
return `${assetsUrl}${imageId}`;
}
// Function to fetch all published posts
export async function getPosts(): Promise<Post[]> {
try {
const postsData = await directus.request(
readItems("posts", {
fields: [
"slug",
"title",
"excerpt",
"featured_image",
"date_created",
"content",
],
filter: {
status: { _eq: "published" },
},
sort: ["-date_created"],
})
);
const posts = postsData.map((post) => ({
...post,
featured_image: getFullImageUrl(post.featured_image),
})) as Post[];
return posts;
} catch (error) {
console.error("Error fetching posts:", error);
return [];
}
}
// Function to fetch a single post by slug
export async function getPostBySlug(
slug: string,
options?: ItemsQuery
): Promise<Post | null> {
try {
const postData = await directus.request(readItem("posts", slug, options));
// Map data to include full image URL
const post = {
...postData,
featured_image: getFullImageUrl(postData.featured_image),
} as Post; // Adjust cast if needed
return post;
} catch (error) {
console.error(`Error fetching post with slug ${slug}:`, error);
return null;
}
}