+
{summary}
{(demoUrl || repoUrl) &&
diff --git a/src/lib/__tests__/appwrite-service.test.ts b/src/lib/__tests__/appwrite-service.test.ts
deleted file mode 100644
index 479ceaa..0000000
--- a/src/lib/__tests__/appwrite-service.test.ts
+++ /dev/null
@@ -1,80 +0,0 @@
-import { describe, it, expect } from 'vitest';
-import { getBlogPosts, getProjects, getWorkExperiences, getLegalDocuments } from '../appwrite-service';
-
-describe('AppWrite Service', () => {
- describe('getBlogPosts', () => {
- it('should return an array of blog posts', async () => {
- const posts = await getBlogPosts();
-
- expect(Array.isArray(posts)).toBe(true);
- expect(posts.length).toBeGreaterThan(0);
-
- // Check that each post has the expected properties
- posts.forEach((post) => {
- expect(post).toHaveProperty('title');
- expect(post).toHaveProperty('summary');
- expect(post).toHaveProperty('date');
- expect(post).toHaveProperty('tags');
- expect(post).toHaveProperty('draft');
- expect(post).toHaveProperty('content');
- expect(post).toHaveProperty('template');
- expect(post).toHaveProperty('featured');
- });
- });
- });
-
- describe('getProjects', () => {
- it('should return an array of projects', async () => {
- const projects = await getProjects();
-
- expect(Array.isArray(projects)).toBe(true);
- expect(projects.length).toBeGreaterThan(0);
-
- // Check that each project has the expected properties
- projects.forEach((project) => {
- expect(project).toHaveProperty('title');
- expect(project).toHaveProperty('summary');
- expect(project).toHaveProperty('date');
- expect(project).toHaveProperty('tags');
- expect(project).toHaveProperty('draft');
- expect(project).toHaveProperty('content');
- expect(project).toHaveProperty('demoUrl');
- expect(project).toHaveProperty('repoUrl');
- });
- });
- });
-
- describe('getWorkExperiences', () => {
- it('should return an array of work experiences', async () => {
- const workExperiences = await getWorkExperiences();
-
- expect(Array.isArray(workExperiences)).toBe(true);
- expect(workExperiences.length).toBeGreaterThan(0);
-
- // Check that each work experience has the expected properties
- workExperiences.forEach((work) => {
- expect(work).toHaveProperty('company');
- expect(work).toHaveProperty('role');
- expect(work).toHaveProperty('dateStart');
- expect(work).toHaveProperty('content');
- expect(work).toHaveProperty('dateEnd');
- });
- });
- });
-
- describe('getLegalDocuments', () => {
- it('should return an array of legal documents', async () => {
- const legalDocuments = await getLegalDocuments();
-
- expect(Array.isArray(legalDocuments)).toBe(true);
- expect(legalDocuments.length).toBeGreaterThan(0);
-
- // Check that each legal document has the expected properties
- legalDocuments.forEach((doc) => {
- expect(doc).toHaveProperty('title');
- expect(doc).toHaveProperty('date');
- expect(doc).toHaveProperty('content');
- });
- });
- });
-});
diff --git a/src/lib/appwrite-service.ts b/src/lib/appwrite-service.ts
deleted file mode 100644
index ed60706..0000000
--- a/src/lib/appwrite-service.ts
+++ /dev/null
@@ -1,396 +0,0 @@
-import type { Models, } from "appwrite";
-import { Query } from "appwrite";
-import { databases, } from "./appwrite"; // Import the already initialized databases instances
-import { remark } from "remark";
-import remarkRehype from "remark-rehype";
-import rehypeStringify from "rehype-stringify";
-
-
-// We're using the storage instance from appwrite.ts which is properly initialized
-// This file only contains service functions and types
-
-/**
- * Convert markdown content to HTML
- */
-export function convertMarkdownToHTML(markdown: string): string {
- if (!markdown) return "";
-
- try {
- const file = remark()
- .use(remarkRehype)
- .use(rehypeStringify)
- .processSync(markdown);
-
- return file.toString();
- } catch (error) {
- console.error("Error converting markdown to HTML:", error);
- return markdown; // Return raw markdown if conversion fails
- }
-}
-
-
-// Types for our collections
-export type BlogPost = Models.Document & {
- title: string;
- summary: string;
- date: Date;
- tags: string[];
- draft: boolean;
- content: string;
- contentHtml?: string; // HTML version of the content
- image?: string; // File ID for the featured image
- template: string; // e.g., "default", "feature", "news"
- featured: boolean;
-};
-
-
-export type Project = Models.Document & {
- title: string;
- summary: string;
- date: Date;
- tags: string[];
- draft: boolean;
- demoUrl?: string;
- repoUrl?: string;
- content: string;
- contentHtml?: string; // HTML version of the content
- image?: string; // File ID for the featured image
-};
-
-
-export type WorkExperience = Models.Document & {
- company: string;
- role: string;
- dateStart: Date;
- content: string;
- contentHtml?: string; // HTML version of the content
- dateEnd: Date | string;
-};
-
-export type LegalDocument = Models.Document & {
- title: string;
- date: Date;
- content: string;
- contentHtml?: string; // HTML version of the content
-};
-
-
-// Define a unified type for search results
-export type SearchEntry = BlogPost | Project;
-
-// Collection IDs - these should be configured based on your Appwrite setup
-
-let blogCollection = '', projectsCollection = '', workCollection = '', legalCollection = '', databaseID = '';
-
-// Check if we're in a server environment (SSR)
-if (typeof window === 'undefined') {
- // Server-side: use environment variables directly
- blogCollection = process?.env?.VITE_APPWRITE_BLOG_COLLECTION_ID || 'blog';
- projectsCollection = process?.env?.VITE_APPWRITE_PROJECTS_COLLECTION_ID || "projects";
- workCollection = process?.env?.VITE_APPWRITE_WORK_COLLECTION_ID || "work";
- legalCollection = process?.env?.VITE_APPWRITE_LEGAL_COLLECTION_ID || "legal";
- databaseID = process.env.VITE_APPWRITE_DATABASE_ID || "main";
-} else {
- blogCollection = import.meta.env.PUBLIC_APPWRITE_BLOG_COLLECTION_ID || 'blog';
- projectsCollection = import.meta.env.PUBLIC_APPWRITE_PROJECTS_COLLECTION_ID || "projects";
- workCollection = import.meta.env.PUBLIC_APPwrite_WORK_COLLECTION_ID || "work";
- legalCollection = import.meta.env.PUBLIC_APPWRITE_LEGAL_COLLECTION_ID || "legal";
- databaseID = import.meta.env.PUBLIC_APPWRITE_DATABASE_ID || "main";
-}
-
-/**
- * Get blog posts from Appwrite database
- */
-export async function getBlogPosts(): Promise
{
- try {
- const response = await databases.listDocuments(
- databaseID,
- blogCollection
- );
-
- // Convert markdown content to HTML for each post
- const postsWithHtml = response.documents.map(post => ({
- ...post,
- contentHtml: convertMarkdownToHTML(post.content)
- }));
-
- return postsWithHtml;
- } catch (error) {
- console.error("Error fetching blog posts:", error);
- throw new Error("Failed to fetch blog posts");
- }
-}
-
-
-/**
- * Get paginated blog posts from Appwrite database
- */
-export async function getBlogPostsPaginated(page: number, limit: number): Promise<{ posts: BlogPost[], total: number }> {
- try {
- // For Appwrite SDK, the correct way to call listDocuments with pagination
- const response = await databases.listDocuments(
- databaseID,
- blogCollection,
- [
- // Only fetch published posts (not drafts)
- Query.equal("draft", false),
- Query.orderDesc('date')
- ]
- );
-
- // Apply pagination manually since Appwrite SDK might not support offset/limit directly in this version
- const paginatedPosts = response.documents.slice((page - 1) * limit, page * limit);
-
- // Convert markdown content to HTML for each post
- const postsWithHtml = paginatedPosts.map(post => ({
- ...post,
- contentHtml: convertMarkdownToHTML(post.content)
- }));
-
- return {
- posts: postsWithHtml,
- total: response.total
- };
- } catch (error) {
- console.error("Error fetching paginated blog posts:", error);
- throw new Error("Failed to fetch paginated blog posts");
- }
-}
-
-
-/**
- * Get a specific blog post by ID
- */
-export async function getBlogPostById(id: string): Promise {
- try {
- const response = await databases.getDocument(
- databaseID,
- blogCollection,
- id
- );
-
- // Convert markdown content to HTML
- return {
- ...response,
- contentHtml: convertMarkdownToHTML(response.content)
- };
- } catch (error) {
- console.error("Error fetching blog post:", error);
- throw new Error("Failed to fetch blog post");
- }
-}
-
-/**
- * Get projects from Appwrite database
- */
-export async function getProjects(): Promise {
- try {
- const response = await databases.listDocuments(
- databaseID,
- projectsCollection,
- [
- // Only fetch published projects (not drafts)
- Query.equal("draft", false),
- Query.orderDesc('date')
- ]
- );
-
- // Convert markdown content to HTML for each project
- const projectsWithHtml = response.documents.map(project => ({
- ...project,
- contentHtml: convertMarkdownToHTML(project.content)
- }));
-
- return projectsWithHtml;
- } catch (error) {
- console.error("Error fetching projects:", error);
- throw new Error("Failed to fetch projects");
- }
-}
-
-
-/**
- * Get paginated projects from Appwrite database
- */
-export async function getProjectsPaginated(page: number, limit: number): Promise<{ posts: Project[], total: number }> {
- try {
- const response = await databases.listDocuments(
- databaseID,
- projectsCollection,
- [
- // Only fetch published projects (not drafts)
- Query.equal("draft", false),
- Query.orderDesc('date')
- ]
- );
-
- // Apply pagination manually since Appwrite SDK might not support offset/limit directly in this version
- const paginatedPosts = response.documents.slice((page - 1) * limit, page * limit);
-
- // Convert markdown content to HTML for each project
- const projectsWithHtml = paginatedPosts.map(project => ({
- ...project,
- contentHtml: convertMarkdownToHTML(project.content)
- }));
-
- return {
- posts: projectsWithHtml,
- total: response.total
- };
- } catch (error) {
- console.error("Error fetching paginated projects:", error);
- throw new Error("Failed to fetch paginated projects");
- }
-}
-
-
-/**
- * Get a specific project by ID
- */
-export async function getProjectById(id: string): Promise {
- try {
- const response = await databases.getDocument(
- databaseID,
- projectsCollection,
- id
- );
-
- // Convert markdown content to HTML
- return {
- ...response,
- contentHtml: convertMarkdownToHTML(response.content)
- };
- } catch (error) {
- console.error("Error fetching project:", error);
- throw new Error("Failed to fetch project");
- }
-}
-
-
-/**
- * Get work experiences from Appwrite database
- */
-export async function getWorkExperiences(): Promise {
- try {
- const response = await databases.listDocuments(
- databaseID,
- workCollection
- );
-
- // Convert markdown content to HTML for each project
- return response.documents.map(work => ({
- ...work,
- contentHtml: convertMarkdownToHTML(work.content)
- }));
- } catch (error) {
- console.error("Error fetching work experiences:", error);
- throw new Error("Failed to fetch work experiences");
- }
-}
-
-/**
- * Get legal documents from Appwrite database
- */
-export async function getLegalDocuments(): Promise {
- try {
- const response = await databases.listDocuments(
- databaseID,
- legalCollection
- );
-
- return response.documents;
- } catch (error) {
- console.error("Error fetching legal documents:", error);
- throw new Error("Failed to fetch legal documents");
- }
-}
-
-/**
- * Perform a search across blog posts and projects using Appwrite SDK
- */
-export async function searchContent(query: string): Promise<{ posts: BlogPost[], projects: Project[] }> {
- try {
- // Search in blog collection for the query term
- const blogResponse = await databases.listDocuments(
- databaseID,
- blogCollection,
- [
- Query.and([
- Query.equal("draft", false),
- Query.or([
- Query.search("title", query),
- Query.search("summary", query),
- Query.search("content", query)
- ])
- ]),
- Query.orderDesc('date')
- ]
- );
-
- // Search in projects collection for the query term
- const projectResponse = await databases.listDocuments(
- databaseID,
- projectsCollection,
- [
- Query.and([
- Query.equal("draft", false),
- Query.or([
- Query.search("title", query),
- Query.search("summary", query),
- Query.search("content", query)
- ])
- ]),
- Query.orderDesc('date')
- ]
- );
-
- // Convert markdown content to HTML for blog posts
- const blogPostsWithHtml = blogResponse.documents.map(post => ({
- ...post,
- contentHtml: convertMarkdownToHTML(post.content)
- }));
-
- // Convert markdown content to HTML for projects
- const projectsWithHtml = projectResponse.documents.map(project => ({
- ...project,
- contentHtml: convertMarkdownToHTML(project.content)
- }));
-
- return {
- posts: blogPostsWithHtml,
- projects: projectsWithHtml
- };
- } catch (error) {
- console.error("Error performing search:", error);
- // More specific error handling for Appwrite errors
- if (error instanceof Error) {
- throw new Error(`Search failed: ${error.message}`);
- }
- throw new Error("Search failed due to an unknown error");
- }
-}
-
-// Remove the duplicate function - keep only the original searchContent function
-// The original searchContent function is already correctly implemented and should be used
-
-
-/**
- * Get a public URL for a file
- */
-export function getFileUrl(bucketId: string, fileId: string): string {
- return `${process.env.VITE_APPWRITE_ENDPOINT}/storage/buckets/${bucketId}/files/${fileId}/view?project=${process.env.VITE_APPWRITE_PROJECT_ID}`;
-}
-
-/**
- * Get a preview URL for a file (thumb or preview)
- */
-export function getFilePreviewUrl(bucketId: string, fileId: string, type: "thumb" | "preview"): string {
- return `${process.env.VITE_APPWRITE_ENDPOINT}/storage/buckets/${bucketId}/files/${fileId}/view?project=${process.env.VITE_APPWRITE_PROJECT_ID}&mode=${type}`;
-}
-
-/**
- * Get a download URL for a file
- */
-export function getFileDownloadUrl(bucketId: string, fileId: string): string {
- return `${process.env.VITE_APPWRITE_ENDPOINT}/storage/buckets/${bucketId}/files/${fileId}/download?project=${process.env.VITE_APPWRITE_PROJECT_ID}`;
-}
diff --git a/src/lib/appwrite.ts b/src/lib/appwrite.ts
deleted file mode 100644
index da4a9b8..0000000
--- a/src/lib/appwrite.ts
+++ /dev/null
@@ -1,32 +0,0 @@
-import { Client, Databases } from "appwrite";
-
-const client = new Client();
-
-// Check if we're in a server environment (SSR)
-if (typeof window === 'undefined') {
- // Server-side: use environment variables directly
- const endpoint = process.env.VITE_APPWRITE_ENDPOINT;
- const projectId = process.env.VITE_APPWRITE_PROJECT_ID;
-
- if (!endpoint || !projectId) {
- throw new Error('Appwrite configuration missing in server environment');
- }
-
- client
- .setEndpoint(endpoint) // Your Appwrite endpoint
- .setProject(projectId); // Your Project ID
-} else {
- // Client-side: use import.meta.env (need to prefix with PUBLIC_ for Astro to make them available)
- const endpoint = import.meta.env.PUBLIC_APPWRITE_ENDPOINT;
- const projectId = import.meta.env.PUBLIC_APPWRITE_PROJECT_ID;
-
- if (!endpoint || !projectId) {
- throw new Error('Appwrite configuration missing in client environment');
- }
-
- client
- .setEndpoint(endpoint) // Your Appwrite endpoint
- .setProject(projectId); // Your Project ID
-}
-
-export const databases = new Databases(client);
diff --git a/src/lib/types.ts b/src/lib/types.ts
new file mode 100644
index 0000000..8e453bf
--- /dev/null
+++ b/src/lib/types.ts
@@ -0,0 +1,39 @@
+export interface BlogPost {
+ id: string;
+ title: string;
+ summary: string;
+ date: string;
+ tags: string[];
+ draft: boolean;
+ content: string;
+ template: string;
+ featured: boolean;
+}
+
+export interface Project {
+ id: string;
+ title: string;
+ summary: string;
+ date: string;
+ tags: string[];
+ draft: boolean;
+ content: string;
+ demoUrl: string;
+ repoUrl: string;
+}
+
+export interface WorkExperience {
+ id: string;
+ company: string;
+ role: string;
+ dateStart: string;
+ dateEnd: string;
+ content: string;
+}
+
+export interface LegalDocument {
+ id: string;
+ title: string;
+ date: string;
+ content: string;
+}
\ No newline at end of file
diff --git a/src/pages/api/assets/[fileID].ts b/src/pages/api/assets/[fileID].ts
deleted file mode 100644
index 9503cb0..0000000
--- a/src/pages/api/assets/[fileID].ts
+++ /dev/null
@@ -1,92 +0,0 @@
-import { type APIRoute } from 'astro';
-import { getFileUrl, getFilePreviewUrl } from '../../../lib/appwrite-service.ts';
-
-export const GET: APIRoute = async ({ params, request }) => {
- const { fileID } = params;
-
- // Validate that we have a file ID
- if (!fileID) {
- return new Response(
- JSON.stringify({ error: 'File ID is required' }),
- { status: 400, headers: { 'Content-Type': 'application/json' } }
- );
- }
-
- try {
- // Get the bucket ID from environment variables
- const bucketId = process.env.VITE_APPWRITE_BUCKET_ID;
-
- if (!bucketId) {
- return new Response(
- JSON.stringify({ error: 'Bucket ID is not configured' }),
- { status: 500, headers: { 'Content-Type': 'application/json' } }
- );
- }
-
- // Parse query parameters for preview type
- const url = new URL(request.url);
- const type = url.searchParams.get('type') as "thumb" | "preview" | null;
-
- let fileUrl: string;
-
- // Determine the appropriate URL based on query parameter or default to view
- if (type === 'thumb' || type === 'preview') {
- fileUrl = getFilePreviewUrl(bucketId, fileID, type);
- } else {
- // Default to regular view URL
- fileUrl = getFileUrl(bucketId, fileID);
- }
-
- // Return a redirect response to the file URL
- return new Response(
- null,
- {
- status: 302,
- headers: {
- 'Location': fileUrl
- }
- }
- );
- } catch (error) {
- console.error('Error fetching file:', error);
- return new Response(
- JSON.stringify({ error: 'Failed to fetch file' }),
- { status: 500, headers: { 'Content-Type': 'application/json' } }
- );
- }
-};
-
-// Handle HEAD requests for preflight checks
-export const HEAD: APIRoute = async ({ params }) => {
- const { fileID } = params;
-
- if (!fileID) {
- return new Response(
- null,
- { status: 400 }
- );
- }
-
- try {
- // Get the bucket ID from environment variables
- const bucketId = process.env.VITE_APPWRITE_BUCKET_ID;
-
- if (!bucketId) {
- return new Response(
- null,
- { status: 500 }
- );
- }
-
- // For HEAD requests, we just validate that the file URL can be generated
- // This is a basic check - in production you might want to actually verify
- // that the file exists on Appwrite
- const fileUrl = getFileUrl(bucketId, fileID);
-
- // Return a successful response (we don't actually need to return anything specific for HEAD)
- return new Response(null, { status: 200 });
- } catch (error) {
- console.error('Error checking file:', error);
- return new Response(null, { status: 500 });
- }
-};
diff --git a/src/pages/blog/[...slug].astro b/src/pages/blog/[...slug].astro
index f841bda..02b7092 100644
--- a/src/pages/blog/[...slug].astro
+++ b/src/pages/blog/[...slug].astro
@@ -1,38 +1,34 @@
---
+import { getCollection } from "astro:content"
import PageLayout from "@layouts/PageLayout.astro"
import TopLayout from "@layouts/TopLayout.astro"
import BottomLayout from "@layouts/BottomLayout.astro"
import ArticleTopLayout from "@layouts/ArticleTopLayout.astro"
import ArticleBottomLayout from "@layouts/ArticleBottomLayout.astro"
-import { getBlogPostById } from "@lib/appwrite-service"
+export const prerender = true
-// Get the requested post
-const slug = Astro.params.slug || ''
-const post = await getBlogPostById(slug)
- .then(blogPost => {
- if (blogPost) {
- return blogPost;
- }
- return null;
- })
- .catch(error => {
- console.error("Error fetching blog post:", error);
- return null;
- })
+export async function getStaticPaths() {
+ const entries = await getCollection("blog", ({ data }) => !data.draft)
+ return entries.map((entry) => ({
+ params: { slug: entry.id },
+ props: { entry: { ...entry, content: entry.rendered?.html }, allEntries: entries },
+ }))
+}
-const { title, summary } = post || { title: "Post not found", summary: "" }
+const { entry, allEntries } = Astro.props
+const { title, summary } = entry.data
---
diff --git a/src/pages/blog/index.astro b/src/pages/blog/index.astro
index b9be979..d1850b8 100644
--- a/src/pages/blog/index.astro
+++ b/src/pages/blog/index.astro
@@ -1,31 +1,25 @@
---
+import { getCollection } from "astro:content"
import PageLayout from "@layouts/PageLayout.astro"
import TopLayout from "@layouts/TopLayout.astro"
import BottomLayout from "@layouts/BottomLayout.astro"
import Blog from "@components/Blog"
import { BLOG } from "@consts"
-import { getBlogPostsPaginated } from "@lib/appwrite-service"
-// Get page and limit from URL parameters
-const url = new URL(typeof window !== 'undefined' ? window.location.href : 'http://localhost')
-const pageParam = url.searchParams.get('page') || '1'
-const limitParam = url.searchParams.get('limit') || '10'
-const page = parseInt(pageParam)
-const limit = parseInt(limitParam)
-
-// Fetch paginated blog posts
-const { posts } = await getBlogPostsPaginated(page, limit)
- .then(result => {
- return result;
- })
- .catch(error => {
- console.error("Error fetching blog posts:", error);
- return { posts: [], total: 0 };
- })
-
-// Get all tags for filtering
-const tags = [...new Set(posts.flatMap(post => post.tags))]
- .sort((a, b) => a.localeCompare(b))
+const entries = await getCollection("blog", ({ data }) => !data.draft)
+const posts = entries.map((entry) => ({
+ id: entry.id,
+ slug: entry.id,
+ title: entry.data.title,
+ summary: entry.data.summary,
+ date: entry.data.date.toISOString(),
+ tags: entry.data.tags,
+ draft: entry.data.draft,
+ content: entry.body ?? "",
+ template: entry.data.template,
+ featured: entry.data.featured,
+}))
+const tags = Array.from(new Set(posts.flatMap((p) => p.tags)))
---
diff --git a/src/pages/index.astro b/src/pages/index.astro
index 2864bd2..ce1faca 100644
--- a/src/pages/index.astro
+++ b/src/pages/index.astro
@@ -1,5 +1,5 @@
---
-import { getBlogPosts, getProjects } from "@lib/appwrite-service";
+import { getCollection } from "astro:content"
import PageLayout from "@layouts/PageLayout.astro"
import ArrowCard from "@components/ArrowCard"
import StackCard from "@components/StackCard.astro"
@@ -7,16 +7,23 @@ import { SITE, SOCIALS } from "@consts"
import TwinklingStars from "@components/TwinklingStars.astro"
import MeteorShower from "@components/MeteorShower.astro"
-// Fetch blog posts and projects from Appwrite
-const posts = (await getBlogPosts())
- .filter(post => !post.draft)
- .sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime())
- .slice(0,3)
+const allBlogEntries = await getCollection("blog", ({ data }) => !data.draft)
+const posts = allBlogEntries.slice(0, 3).map((entry) => ({
+ $id: entry.id,
+ title: entry.data.title,
+ summary: entry.data.summary,
+ date: entry.data.date,
+ tags: entry.data.tags,
+}))
-const projects = (await getProjects())
- .filter(project => !project.draft)
- .sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime())
- .slice(0,3)
+const allProjectEntries = await getCollection("projects", ({ data }) => !data.draft)
+const projects = allProjectEntries.slice(0, 3).map((entry) => ({
+ $id: entry.id,
+ title: entry.data.title,
+ summary: entry.data.summary,
+ date: entry.data.date,
+ tags: entry.data.tags,
+}))
const stack = [
{
@@ -38,11 +45,6 @@ const stack = [
text: "Tailwind",
icon: "tailwind",
href: "https://tailwindcss.com"
- },
- {
- text: "Appwrite",
- icon: "simple-icons--appwrite",
- href: "https://appwrite.io"
}
]
---
@@ -83,9 +85,9 @@ const stack = [