mirror of
https://github.com/OwethuManagedServices/oms-website-nextjs.git
synced 2025-12-17 17:18:09 +00:00
feature: intergrated directus for posts
This commit is contained in:
5
lib/directus.ts
Normal file
5
lib/directus.ts
Normal file
@ -0,0 +1,5 @@
|
||||
import { createDirectus, rest } from "@directus/sdk";
|
||||
|
||||
export const directus = createDirectus(
|
||||
String(process.env.DIRECTUS_API_ENDPOINT!)
|
||||
).with(rest());
|
||||
8
lib/query/home.ts
Normal file
8
lib/query/home.ts
Normal 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
66
lib/query/post.ts
Normal 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;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user