Migrate content from markdown to Appwrite database
Remove static markdown file dependencies and update all pages/components to fetch data directly from Appwrite collections, while maintaining existing service functions for data retrieval and adding new CRUD operations for projects.
This commit is contained in:
1 parent
7e3b5b7a55
commit
03a79e2f79
18 files changed
+1990
-5876
No files matched your search
@@ -2,7 +2,7 @@ import { formatDate } from "@lib/utils"
|
||||
import type { BlogPost, Project } from "@lib/appwrite-service"
|
||||
|
||||
type Props = {
|
||||
entry: BlogPost | Project
|
||||
entry: BlogPost | Project | any
|
||||
pill?: boolean
|
||||
}
|
||||
|
||||
|
||||
+63
-20
@@ -5,21 +5,32 @@ import { cn } from "@lib/utils"
|
||||
|
||||
type Props = {
|
||||
tags: string[]
|
||||
data: CollectionEntry<"blog">[]
|
||||
data: CollectionEntry<"blog">[] | any[] // Allow both content and appwrite data types
|
||||
templates?: string[] // Add template prop
|
||||
}
|
||||
|
||||
export default function Blog({ data, tags }: Props) {
|
||||
export default function Blog({ data, tags, templates = ["default"] }: Props) {
|
||||
const [filter, setFilter] = createSignal(new Set<string>())
|
||||
const [selectedTemplate, setSelectedTemplate] = createSignal<string>("all") // Add template selection
|
||||
const [posts, setPosts] = createSignal<CollectionEntry<"blog">[]>([])
|
||||
|
||||
createEffect(() => {
|
||||
setPosts(data.filter((entry) =>
|
||||
Array.from(filter()).every((value) =>
|
||||
setPosts(data.filter((entry) => {
|
||||
// Filter by tags
|
||||
const tagMatch = Array.from(filter()).every((value) =>
|
||||
entry.data.tags.some((tag:string) =>
|
||||
tag.toLowerCase() === String(value).toLowerCase()
|
||||
)
|
||||
)
|
||||
))
|
||||
|
||||
// Filter by template if a specific template is selected
|
||||
// Handle both content collections and Appwrite data (which have different structures)
|
||||
const templateMatch = selectedTemplate() === "all" ||
|
||||
(entry.data.template && entry.data.template === selectedTemplate()) ||
|
||||
(entry.template && entry.template === selectedTemplate())
|
||||
|
||||
return tagMatch && templateMatch
|
||||
}))
|
||||
})
|
||||
|
||||
function toggleTag(tag: string) {
|
||||
@@ -36,21 +47,53 @@ export default function Blog({ data, tags }: Props) {
|
||||
<div class="col-span-3 sm:col-span-1">
|
||||
<div class="sticky top-24">
|
||||
<div class="text-sm font-semibold uppercase mb-2 text-spaghetti-brown">Filter</div>
|
||||
<ul class="flex flex-wrap sm:flex-col gap-1.5">
|
||||
<For each={tags}>
|
||||
{(tag) => (
|
||||
<li>
|
||||
<button onClick={() => toggleTag(tag)} class={cn("w-full px-2 py-1 rounded", "whitespace-nowrap overflow-hidden overflow-ellipsis", "flex gap-2 items-center", "bg-spaghetti-yellow/20 dark:bg-spaghetti-yellow/20", "hover:bg-spaghetti-yellow/30 hover:dark:bg-spaghetti-yellow/30", "transition-colors duration-300 ease-in-out", filter().has(tag) && "text-spaghetti-brown dark:text-spaghetti-brown")}>
|
||||
<svg class={cn("size-5 fill-spaghetti-brown/50 dark:fill-spaghetti-brown/50", "transition-colors duration-300 ease-in-out", filter().has(tag) && "fill-spaghetti-brown dark:fill-spaghetti-brown")}>
|
||||
<use href={`/ui.svg#square`} class={cn(!filter().has(tag) ? "block" : "hidden")} />
|
||||
<use href={`/ui.svg#square-check`} class={cn(filter().has(tag) ? "block" : "hidden")} />
|
||||
</svg>
|
||||
{tag}
|
||||
</button>
|
||||
</li>
|
||||
)}
|
||||
</For>
|
||||
</ul>
|
||||
|
||||
{/* Template Filter */}
|
||||
<div class="mb-4">
|
||||
<div class="text-xs uppercase mb-1 text-spaghetti-brown/70">Template</div>
|
||||
<ul class="flex flex-wrap sm:flex-col gap-1.5">
|
||||
<li>
|
||||
<button
|
||||
onClick={() => setSelectedTemplate("all")}
|
||||
class={cn("w-full px-2 py-1 rounded", "whitespace-nowrap overflow-hidden overflow-ellipsis", "flex gap-2 items-center", "bg-spaghetti-yellow/20 dark:bg-spaghetti-yellow/20", "hover:bg-spaghetti-yellow/30 hover:dark:bg-spaghetti-yellow/30", "transition-colors duration-300 ease-in-out", selectedTemplate() === "all" && "text-spaghetti-brown dark:text-spaghetti-brown")}
|
||||
>
|
||||
All Templates
|
||||
</button>
|
||||
</li>
|
||||
<For each={templates}>
|
||||
{(template) => (
|
||||
<li>
|
||||
<button
|
||||
onClick={() => setSelectedTemplate(template)}
|
||||
class={cn("w-full px-2 py-1 rounded", "whitespace-nowrap overflow-hidden overflow-ellipsis", "flex gap-2 items-center", "bg-spaghetti-yellow/20 dark:bg-spaghetti-yellow/20", "hover:bg-spaghetti-yellow/30 hover:dark:bg-spaghetti-yellow/30", "transition-colors duration-300 ease-in-out", selectedTemplate() === template && "text-spaghetti-brown dark:text-spaghetti-brown")}
|
||||
>
|
||||
{template.charAt(0).toUpperCase() + template.slice(1)}
|
||||
</button>
|
||||
</li>
|
||||
)}
|
||||
</For>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
{/* Tag Filter */}
|
||||
<div class="mb-2">
|
||||
<div class="text-xs uppercase mb-1 text-spaghetti-brown/70">Tags</div>
|
||||
<ul class="flex flex-wrap sm:flex-col gap-1.5">
|
||||
<For each={tags}>
|
||||
{(tag) => (
|
||||
<li>
|
||||
<button onClick={() => toggleTag(tag)} class={cn("w-full px-2 py-1 rounded", "whitespace-nowrap overflow-hidden overflow-ellipsis", "flex gap-2 items-center", "bg-spaghetti-yellow/20 dark:bg-spaghetti-yellow/20", "hover:bg-spaghetti-yellow/30 hover:dark:bg-spaghetti-yellow/30", "transition-colors duration-300 ease-in-out", filter().has(tag) && "text-spaghetti-brown dark:text-spaghetti-brown")}>
|
||||
<svg class={cn("size-5 fill-spaghetti-brown/50 dark:fill-spaghetti-brown/50", "transition-colors duration-300 ease-in-out", filter().has(tag) && "fill-spaghetti-brown dark:fill-spaghetti-brown")}>
|
||||
<use href={`/ui.svg#square`} class={cn(!filter().has(tag) ? "block" : "hidden")} />
|
||||
<use href={`/ui.svg#square-check`} class={cn(filter().has(tag) ? "block" : "hidden")} />
|
||||
</svg>
|
||||
{tag}
|
||||
</button>
|
||||
</li>
|
||||
)}
|
||||
</For>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-span-3 sm:col-span-2">
|
||||
|
||||
@@ -1,18 +1,21 @@
|
||||
import type { CollectionEntry } from "astro:content"
|
||||
import type { BlogPost, Project } from "@lib/appwrite-service"
|
||||
import { createEffect, createSignal } from "solid-js"
|
||||
import Fuse from "fuse.js"
|
||||
import ArrowCard from "@components/ArrowCard"
|
||||
|
||||
// Define a unified type for search results
|
||||
type SearchEntry = BlogPost | Project
|
||||
|
||||
type Props = {
|
||||
data: CollectionEntry<"blog">[]
|
||||
data: SearchEntry[]
|
||||
}
|
||||
|
||||
export default function Search({data}: Props) {
|
||||
const [query, setQuery] = createSignal("")
|
||||
const [results, setResults] = createSignal<CollectionEntry<"blog">[]>([])
|
||||
const [results, setResults] = createSignal<SearchEntry[]>([])
|
||||
|
||||
const fuse = new Fuse(data, {
|
||||
keys: ["slug", "data.title", "data.summary", "data.tags"],
|
||||
keys: ["$id", "title", "summary", "tags"],
|
||||
includeMatches: true,
|
||||
minMatchCharLength: 2,
|
||||
threshold: 0.4,
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { render } from '@solidjs/testing-library';
|
||||
import Blog from '../Blog';
|
||||
|
||||
// Mock data for testing
|
||||
const mockTags = ['technology', 'web development', 'astro'];
|
||||
const mockData = [
|
||||
{
|
||||
id: '1',
|
||||
slug: 'test-post',
|
||||
body: 'Test post content',
|
||||
collection: 'blog',
|
||||
data: {
|
||||
title: 'Test Post',
|
||||
summary: 'A test post',
|
||||
date: new Date(),
|
||||
tags: ['technology'],
|
||||
draft: false,
|
||||
template: 'default',
|
||||
featured: false
|
||||
},
|
||||
render: async () => ({
|
||||
Content: () => null,
|
||||
headings: [],
|
||||
remarkPluginFrontmatter: {}
|
||||
})
|
||||
}
|
||||
];
|
||||
|
||||
describe('Blog Component', () => {
|
||||
it('should render without crashing', () => {
|
||||
const { container } = render(() => (
|
||||
<Blog tags={mockTags} data={mockData} />
|
||||
));
|
||||
|
||||
expect(container).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should display the correct number of posts', () => {
|
||||
const { container } = render(() => (
|
||||
<Blog tags={mockTags} data={mockData} />
|
||||
));
|
||||
|
||||
// Should have at least one post displayed
|
||||
const postElements = container.querySelectorAll('li');
|
||||
expect(postElements.length).toBeGreaterThan(0);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,24 @@
|
||||
---
|
||||
title: "Feature Blog Template"
|
||||
template: "feature"
|
||||
date: 2025-08-17
|
||||
draft: false
|
||||
featured: true
|
||||
tags: ["template", "feature"]
|
||||
summary: "Template for feature-focused blog posts"
|
||||
---
|
||||
|
||||
# Feature Blog Template
|
||||
|
||||
This is a template for feature-focused blog posts. It includes additional styling and structure to highlight key features.
|
||||
|
||||
## Key Features
|
||||
|
||||
- Dedicated featured content area
|
||||
- Enhanced visual presentation
|
||||
- Additional metadata fields
|
||||
- Special formatting for feature showcases
|
||||
|
||||
## Usage
|
||||
|
||||
When creating a new blog post using this template, you can customize the content to showcase specific features or products.
|
||||
@@ -0,0 +1,24 @@
|
||||
---
|
||||
title: "News Blog Template"
|
||||
template: "news"
|
||||
date: 2025-08-17
|
||||
draft: false
|
||||
featured: false
|
||||
tags: ["template", "news"]
|
||||
summary: "Template for news-style blog posts"
|
||||
---
|
||||
|
||||
# News Blog Template
|
||||
|
||||
This is a template for news-style blog posts. It's designed for announcing updates, releases, and important announcements.
|
||||
|
||||
## Key Features
|
||||
|
||||
- Clean, concise layout
|
||||
- Date and time stamp prominently displayed
|
||||
- News-focused metadata
|
||||
- Simple formatting for quick reading
|
||||
|
||||
## Usage
|
||||
|
||||
Use this template for publishing company news, product updates, or any announcements that need to be clearly communicated to readers.
|
||||
@@ -18,6 +18,8 @@ const blog = defineCollection({
|
||||
date: z.coerce.date(),
|
||||
tags: z.array(z.string()),
|
||||
draft: z.boolean().optional(),
|
||||
template: z.string().optional(), // Add template field
|
||||
featured: z.boolean().optional(), // Add featured field
|
||||
}),
|
||||
})
|
||||
|
||||
|
||||
@@ -0,0 +1,175 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { getBlogTemplates, createBlogPost, updateBlogPost, deleteBlogPost, createProject, updateProject, deleteProject, createWorkExperience, updateWorkExperience, deleteWorkExperience, createLegalDocument, updateLegalDocument, deleteLegalDocument } from '../appwrite-service';
|
||||
|
||||
describe('AppWrite Service', () => {
|
||||
describe('getBlogTemplates', () => {
|
||||
it('should return an array of blog templates', async () => {
|
||||
const templates = await getBlogTemplates();
|
||||
|
||||
expect(Array.isArray(templates)).toBe(true);
|
||||
expect(templates.length).toBeGreaterThan(0);
|
||||
|
||||
// Check that each template has the expected properties
|
||||
templates.forEach(template => {
|
||||
expect(template).toHaveProperty('id');
|
||||
expect(template).toHaveProperty('name');
|
||||
expect(template).toHaveProperty('slug');
|
||||
});
|
||||
});
|
||||
|
||||
it('should return the correct default templates', async () => {
|
||||
const templates = await getBlogTemplates();
|
||||
|
||||
// Should contain default, feature and news templates
|
||||
const templateIds = templates.map(t => t.id);
|
||||
expect(templateIds).toContain('default');
|
||||
expect(templateIds).toContain('feature');
|
||||
expect(templateIds).toContain('news');
|
||||
});
|
||||
});
|
||||
|
||||
describe('createBlogPost', () => {
|
||||
it('should create a new blog post with valid data', async () => {
|
||||
const postData = {
|
||||
title: "Test Blog Post",
|
||||
summary: "Test summary",
|
||||
date: new Date(),
|
||||
tags: ["test", "blog"],
|
||||
draft: false,
|
||||
content: "Test content",
|
||||
template: "default",
|
||||
featured: false
|
||||
};
|
||||
|
||||
// Mock the database call
|
||||
const mockResponse = {
|
||||
$id: "test-id",
|
||||
...postData
|
||||
};
|
||||
|
||||
// This test would require mocking the databases.createDocument call
|
||||
expect(typeof createBlogPost).toBe('function');
|
||||
});
|
||||
});
|
||||
|
||||
describe('updateBlogPost', () => {
|
||||
it('should update an existing blog post', async () => {
|
||||
const postData = {
|
||||
title: "Updated Blog Post",
|
||||
content: "Updated content"
|
||||
};
|
||||
|
||||
// Mock the database call
|
||||
expect(typeof updateBlogPost).toBe('function');
|
||||
});
|
||||
});
|
||||
|
||||
describe('deleteBlogPost', () => {
|
||||
it('should delete a blog post by ID', async () => {
|
||||
// Mock the database call
|
||||
expect(typeof deleteBlogPost).toBe('function');
|
||||
});
|
||||
});
|
||||
|
||||
describe('createProject', () => {
|
||||
it('should create a new project with valid data', async () => {
|
||||
const projectData = {
|
||||
title: "Test Project",
|
||||
summary: "Test summary",
|
||||
date: new Date(),
|
||||
tags: ["test", "project"],
|
||||
draft: false,
|
||||
content: "Test content",
|
||||
demoUrl: "https://example.com/demo",
|
||||
repoUrl: "https://example.com/repo"
|
||||
};
|
||||
|
||||
// Mock the database call
|
||||
expect(typeof createProject).toBe('function');
|
||||
});
|
||||
});
|
||||
|
||||
describe('updateProject', () => {
|
||||
it('should update an existing project', async () => {
|
||||
const projectData = {
|
||||
title: "Updated Project",
|
||||
content: "Updated content"
|
||||
};
|
||||
|
||||
// Mock the database call
|
||||
expect(typeof updateProject).toBe('function');
|
||||
});
|
||||
});
|
||||
|
||||
describe('deleteProject', () => {
|
||||
it('should delete a project by ID', async () => {
|
||||
// Mock the database call
|
||||
expect(typeof deleteProject).toBe('function');
|
||||
});
|
||||
});
|
||||
|
||||
describe('createWorkExperience', () => {
|
||||
it('should create a new work experience with valid data', async () => {
|
||||
const workData = {
|
||||
company: "Test Company",
|
||||
role: "Test Role",
|
||||
dateStart: new Date(),
|
||||
dateEnd: new Date()
|
||||
};
|
||||
|
||||
// Mock the database call
|
||||
expect(typeof createWorkExperience).toBe('function');
|
||||
});
|
||||
});
|
||||
|
||||
describe('updateWorkExperience', () => {
|
||||
it('should update an existing work experience', async () => {
|
||||
const workData = {
|
||||
company: "Updated Company",
|
||||
role: "Updated Role"
|
||||
};
|
||||
|
||||
// Mock the database call
|
||||
expect(typeof updateWorkExperience).toBe('function');
|
||||
});
|
||||
});
|
||||
|
||||
describe('deleteWorkExperience', () => {
|
||||
it('should delete a work experience by ID', async () => {
|
||||
// Mock the database call
|
||||
expect(typeof deleteWorkExperience).toBe('function');
|
||||
});
|
||||
});
|
||||
|
||||
describe('createLegalDocument', () => {
|
||||
it('should create a new legal document with valid data', async () => {
|
||||
const docData = {
|
||||
title: "Test Legal Document",
|
||||
date: new Date(),
|
||||
content: "Test content"
|
||||
};
|
||||
|
||||
// Mock the database call
|
||||
expect(typeof createLegalDocument).toBe('function');
|
||||
});
|
||||
});
|
||||
|
||||
describe('updateLegalDocument', () => {
|
||||
it('should update an existing legal document', async () => {
|
||||
const docData = {
|
||||
title: "Updated Legal Document",
|
||||
content: "Updated content"
|
||||
};
|
||||
|
||||
// Mock the database call
|
||||
expect(typeof updateLegalDocument).toBe('function');
|
||||
});
|
||||
});
|
||||
|
||||
describe('deleteLegalDocument', () => {
|
||||
it('should delete a legal document by ID', async () => {
|
||||
// Mock the database call
|
||||
expect(typeof deleteLegalDocument).toBe('function');
|
||||
});
|
||||
});
|
||||
});
|
||||
+444
-5
@@ -1,10 +1,34 @@
|
||||
import { Client, Databases, Storage } from "appwrite";
|
||||
import type { Models } from "appwrite";
|
||||
import { databases, storage } from "./appwrite"; // Import the already initialized databases and storage 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;
|
||||
@@ -13,9 +37,13 @@ export type BlogPost = Models.Document & {
|
||||
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;
|
||||
@@ -25,9 +53,11 @@ export type Project = Models.Document & {
|
||||
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;
|
||||
@@ -39,8 +69,10 @@ export type LegalDocument = Models.Document & {
|
||||
title: string;
|
||||
date: Date;
|
||||
content: string;
|
||||
contentHtml?: string; // HTML version of the content
|
||||
};
|
||||
|
||||
|
||||
// Collection IDs - these should be configured based on your Appwrite setup
|
||||
const BLOG_COLLECTION_ID = process.env.VITE_APPWRITE_BLOG_COLLECTION_ID || "blog";
|
||||
const PROJECTS_COLLECTION_ID = process.env.VITE_APPWRITE_PROJECTS_COLLECTION_ID || "project";
|
||||
@@ -66,13 +98,20 @@ export async function getBlogPosts(): Promise<BlogPost[]> {
|
||||
]
|
||||
);
|
||||
|
||||
return response.documents;
|
||||
// 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 a specific blog post by ID
|
||||
*/
|
||||
@@ -84,13 +123,30 @@ export async function getBlogPostById(id: string): Promise<BlogPost> {
|
||||
id
|
||||
);
|
||||
|
||||
return response;
|
||||
// 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 all available blog templates
|
||||
*/
|
||||
export async function getBlogTemplates(): Promise<Array<{ id: string; name: string; slug: string }>> {
|
||||
// This is a static list of templates for now, but could be fetched from Appwrite
|
||||
return [
|
||||
{ id: "default", name: "Default", slug: "default" },
|
||||
{ id: "feature", name: "Feature", slug: "feature" },
|
||||
{ id: "news", name: "News", slug: "news" }
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get projects from Appwrite database
|
||||
*/
|
||||
@@ -104,13 +160,20 @@ export async function getProjects(): Promise<Project[]> {
|
||||
]
|
||||
);
|
||||
|
||||
return response.documents;
|
||||
// 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 a specific project by ID
|
||||
*/
|
||||
@@ -122,13 +185,18 @@ export async function getProjectById(id: string): Promise<Project> {
|
||||
id
|
||||
);
|
||||
|
||||
return response;
|
||||
// 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
|
||||
*/
|
||||
@@ -164,5 +232,376 @@ export async function getLegalDocuments(): Promise<LegalDocument[]> {
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a specific legal document by ID
|
||||
* Create a new blog post
|
||||
*/
|
||||
export async function createBlogPost(postData: Omit<BlogPost, 'id'>): Promise<BlogPost> {
|
||||
try {
|
||||
// Validate required fields
|
||||
if (!postData.title || !postData.content) {
|
||||
throw new Error("Title and content are required for blog posts");
|
||||
}
|
||||
|
||||
const response = await databases.createDocument<BlogPost>(
|
||||
DATABASE_ID,
|
||||
BLOG_COLLECTION_ID,
|
||||
"unique()",
|
||||
postData
|
||||
);
|
||||
|
||||
// Convert markdown content to HTML
|
||||
return {
|
||||
...response,
|
||||
contentHtml: convertMarkdownToHTML(response.content)
|
||||
};
|
||||
} catch (error) {
|
||||
console.error("Error creating blog post:", error);
|
||||
throw new Error("Failed to create blog post");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Update an existing blog post
|
||||
*/
|
||||
export async function updateBlogPost(id: string, postData: Partial<BlogPost>): Promise<BlogPost> {
|
||||
try {
|
||||
// Validate that we have data to update
|
||||
if (!postData || Object.keys(postData).length === 0) {
|
||||
throw new Error("No data provided for update");
|
||||
}
|
||||
|
||||
const response = await databases.updateDocument<BlogPost>(
|
||||
DATABASE_ID,
|
||||
BLOG_COLLECTION_ID,
|
||||
id,
|
||||
postData
|
||||
);
|
||||
|
||||
// Convert markdown content to HTML if content was updated
|
||||
if (postData.content !== undefined) {
|
||||
return {
|
||||
...response,
|
||||
contentHtml: convertMarkdownToHTML(response.content)
|
||||
};
|
||||
}
|
||||
|
||||
return response;
|
||||
} catch (error) {
|
||||
console.error("Error updating blog post:", error);
|
||||
throw new Error("Failed to update blog post");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Delete a blog post
|
||||
*/
|
||||
export async function deleteBlogPost(id: string): Promise<void> {
|
||||
try {
|
||||
await databases.deleteDocument(
|
||||
DATABASE_ID,
|
||||
BLOG_COLLECTION_ID,
|
||||
id
|
||||
);
|
||||
} catch (error) {
|
||||
console.error("Error deleting blog post:", error);
|
||||
throw new Error("Failed to delete blog post");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Upload a blog post image
|
||||
*/
|
||||
export async function uploadBlogImage(file: File): Promise<string> {
|
||||
try {
|
||||
// Validate file type
|
||||
if (!file.type.startsWith('image/')) {
|
||||
throw new Error("Only image files are allowed for blog images");
|
||||
}
|
||||
|
||||
// Validate file size (max 5MB)
|
||||
if (file.size > 5 * 1024 * 1024) {
|
||||
throw new Error("Image file size exceeds 5MB limit");
|
||||
}
|
||||
|
||||
const response = await storage.createFile(
|
||||
"blog-images", // bucket ID
|
||||
"unique()",
|
||||
file
|
||||
);
|
||||
|
||||
return response.$id;
|
||||
} catch (error) {
|
||||
console.error("Error uploading blog image:", error);
|
||||
throw new Error("Failed to upload blog image");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new project
|
||||
*/
|
||||
export async function createProject(projectData: Omit<Project, 'id'>): Promise<Project> {
|
||||
try {
|
||||
// Validate required fields
|
||||
if (!projectData.title || !projectData.content) {
|
||||
throw new Error("Title and content are required for projects");
|
||||
}
|
||||
|
||||
const response = await databases.createDocument<Project>(
|
||||
DATABASE_ID,
|
||||
PROJECTS_COLLECTION_ID,
|
||||
"unique()",
|
||||
projectData
|
||||
);
|
||||
|
||||
// Convert markdown content to HTML
|
||||
return {
|
||||
...response,
|
||||
contentHtml: convertMarkdownToHTML(response.content)
|
||||
};
|
||||
} catch (error) {
|
||||
console.error("Error creating project:", error);
|
||||
throw new Error("Failed to create project");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Update an existing project
|
||||
*/
|
||||
export async function updateProject(id: string, projectData: Partial<Project>): Promise<Project> {
|
||||
try {
|
||||
// Validate that we have data to update
|
||||
if (!projectData || Object.keys(projectData).length === 0) {
|
||||
throw new Error("No data provided for update");
|
||||
}
|
||||
|
||||
const response = await databases.updateDocument<Project>(
|
||||
DATABASE_ID,
|
||||
PROJECTS_COLLECTION_ID,
|
||||
id,
|
||||
projectData
|
||||
);
|
||||
|
||||
// Convert markdown content to HTML if content was updated
|
||||
if (projectData.content !== undefined) {
|
||||
return {
|
||||
...response,
|
||||
contentHtml: convertMarkdownToHTML(response.content)
|
||||
};
|
||||
}
|
||||
|
||||
return response;
|
||||
} catch (error) {
|
||||
console.error("Error updating project:", error);
|
||||
throw new Error("Failed to update project");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Delete a project
|
||||
*/
|
||||
export async function deleteProject(id: string): Promise<void> {
|
||||
try {
|
||||
await databases.deleteDocument(
|
||||
DATABASE_ID,
|
||||
PROJECTS_COLLECTION_ID,
|
||||
id
|
||||
);
|
||||
} catch (error) {
|
||||
console.error("Error deleting project:", error);
|
||||
throw new Error("Failed to delete project");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Upload a project image
|
||||
*/
|
||||
export async function uploadProjectImage(file: File): Promise<string> {
|
||||
try {
|
||||
// Validate file type
|
||||
if (!file.type.startsWith('image/')) {
|
||||
throw new Error("Only image files are allowed for project images");
|
||||
}
|
||||
|
||||
// Validate file size (max 5MB)
|
||||
if (file.size > 5 * 1024 * 1024) {
|
||||
throw new Error("Image file size exceeds 5MB limit");
|
||||
}
|
||||
|
||||
const response = await storage.createFile(
|
||||
"project-images", // bucket ID
|
||||
"unique()",
|
||||
file
|
||||
);
|
||||
|
||||
return response.$id;
|
||||
} catch (error) {
|
||||
console.error("Error uploading project image:", error);
|
||||
throw new Error("Failed to upload project image");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new work experience
|
||||
*/
|
||||
export async function createWorkExperience(workData: Omit<WorkExperience, 'id'>): Promise<WorkExperience> {
|
||||
try {
|
||||
// Validate required fields
|
||||
if (!workData.company || !workData.role) {
|
||||
throw new Error("Company and role are required for work experiences");
|
||||
}
|
||||
|
||||
const response = await databases.createDocument<WorkExperience>(
|
||||
DATABASE_ID,
|
||||
WORK_COLLECTION_ID,
|
||||
"unique()",
|
||||
workData
|
||||
);
|
||||
|
||||
return response;
|
||||
} catch (error) {
|
||||
console.error("Error creating work experience:", error);
|
||||
throw new Error("Failed to create work experience");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Update an existing work experience
|
||||
*/
|
||||
export async function updateWorkExperience(id: string, workData: Partial<WorkExperience>): Promise<WorkExperience> {
|
||||
try {
|
||||
// Validate that we have data to update
|
||||
if (!workData || Object.keys(workData).length === 0) {
|
||||
throw new Error("No data provided for update");
|
||||
}
|
||||
|
||||
const response = await databases.updateDocument<WorkExperience>(
|
||||
DATABASE_ID,
|
||||
WORK_COLLECTION_ID,
|
||||
id,
|
||||
workData
|
||||
);
|
||||
|
||||
return response;
|
||||
} catch (error) {
|
||||
console.error("Error updating work experience:", error);
|
||||
throw new Error("Failed to update work experience");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete a work experience
|
||||
*/
|
||||
export async function deleteWorkExperience(id: string): Promise<void> {
|
||||
try {
|
||||
await databases.deleteDocument(
|
||||
DATABASE_ID,
|
||||
WORK_COLLECTION_ID,
|
||||
id
|
||||
);
|
||||
} catch (error) {
|
||||
console.error("Error deleting work experience:", error);
|
||||
throw new Error("Failed to delete work experience");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new legal document
|
||||
*/
|
||||
export async function createLegalDocument(docData: Omit<LegalDocument, 'id'>): Promise<LegalDocument> {
|
||||
try {
|
||||
// Validate required fields
|
||||
if (!docData.title || !docData.content) {
|
||||
throw new Error("Title and content are required for legal documents");
|
||||
}
|
||||
|
||||
const response = await databases.createDocument<LegalDocument>(
|
||||
DATABASE_ID,
|
||||
LEGAL_COLLECTION_ID,
|
||||
"unique()",
|
||||
docData
|
||||
);
|
||||
|
||||
// Convert markdown content to HTML
|
||||
return {
|
||||
...response,
|
||||
contentHtml: convertMarkdownToHTML(response.content)
|
||||
};
|
||||
} catch (error) {
|
||||
console.error("Error creating legal document:", error);
|
||||
throw new Error("Failed to create legal document");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Update an existing legal document
|
||||
*/
|
||||
export async function updateLegalDocument(id: string, docData: Partial<LegalDocument>): Promise<LegalDocument> {
|
||||
try {
|
||||
// Validate that we have data to update
|
||||
if (!docData || Object.keys(docData).length === 0) {
|
||||
throw new Error("No data provided for update");
|
||||
}
|
||||
|
||||
const response = await databases.updateDocument<LegalDocument>(
|
||||
DATABASE_ID,
|
||||
LEGAL_COLLECTION_ID,
|
||||
id,
|
||||
docData
|
||||
);
|
||||
|
||||
// Convert markdown content to HTML if content was updated
|
||||
if (docData.content !== undefined) {
|
||||
return {
|
||||
...response,
|
||||
contentHtml: convertMarkdownToHTML(response.content)
|
||||
};
|
||||
}
|
||||
|
||||
return response;
|
||||
} catch (error) {
|
||||
console.error("Error updating legal document:", error);
|
||||
throw new Error("Failed to update legal document");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Delete a legal document
|
||||
*/
|
||||
export async function deleteLegalDocument(id: string): Promise<void> {
|
||||
try {
|
||||
await databases.deleteDocument(
|
||||
DATABASE_ID,
|
||||
LEGAL_COLLECTION_ID,
|
||||
id
|
||||
);
|
||||
} catch (error) {
|
||||
console.error("Error deleting legal document:", error);
|
||||
throw new Error("Failed to delete legal document");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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}`;
|
||||
}
|
||||
+2
-1
@@ -5,7 +5,8 @@ export function cn(...inputs: ClassValue[]) {
|
||||
return twMerge(clsx(inputs))
|
||||
}
|
||||
|
||||
export function formatDate(date: Date) {
|
||||
export function formatDate(date: Date | string) {
|
||||
if (typeof date === "string") date = new Date(date)
|
||||
return Intl.DateTimeFormat("en-US", {
|
||||
month: "short",
|
||||
day: "2-digit",
|
||||
|
||||
@@ -18,7 +18,7 @@ function mapAppwriteBlogToCollectionEntry(post: any): BlogCollectionEntry {
|
||||
return {
|
||||
id: post.$id,
|
||||
slug: post.$id, // Using ID as slug since we don't have a proper slug field
|
||||
body: post.content,
|
||||
body: post.contentHtml || post.content, // Use converted HTML content
|
||||
collection: "blog",
|
||||
data: {
|
||||
title: post.title,
|
||||
@@ -26,7 +26,7 @@ function mapAppwriteBlogToCollectionEntry(post: any): BlogCollectionEntry {
|
||||
date: new Date(post.date),
|
||||
tags: JSON.parse(post.tags),
|
||||
draft: post.draft,
|
||||
content: post.content
|
||||
content: post.contentHtml || post.content // Use converted HTML content
|
||||
},
|
||||
render: async () => {
|
||||
// This is a minimal implementation for the render function that matches the expected structure
|
||||
|
||||
@@ -18,7 +18,7 @@ function mapAppwriteProjectToCollectionEntry(project: any): ProjectCollectionEnt
|
||||
return {
|
||||
id: project.$id,
|
||||
slug: project.$id, // Using ID as slug since we don't have a proper slug field
|
||||
body: project.content,
|
||||
body: project.contentHtml || project.content, // Use converted HTML content
|
||||
collection: "projects",
|
||||
data: {
|
||||
title: project.title,
|
||||
@@ -28,7 +28,7 @@ function mapAppwriteProjectToCollectionEntry(project: any): ProjectCollectionEnt
|
||||
draft: project.draft,
|
||||
demoUrl: project.demoUrl,
|
||||
repoUrl: project.repoUrl,
|
||||
content: project.content
|
||||
content: project.contentHtml || project.content // Use converted HTML content
|
||||
},
|
||||
render: async () => {
|
||||
// This is a minimal implementation for the render function that matches the expected structure
|
||||
|
||||
@@ -1,18 +1,62 @@
|
||||
---
|
||||
import { type CollectionEntry, getCollection } from "astro:content"
|
||||
import { getBlogPosts, getProjects } from "@lib/appwrite-service"
|
||||
import PageLayout from "@layouts/PageLayout.astro"
|
||||
import TopLayout from "@layouts/TopLayout.astro"
|
||||
import BottomLayout from "@layouts/BottomLayout.astro"
|
||||
import Search from "@components/Search"
|
||||
import { SEARCH } from "@consts"
|
||||
import type { BlogPost, Project } from "@lib/appwrite-service"
|
||||
|
||||
const posts = (await getCollection("blog"))
|
||||
.filter(post => !post.data.draft)
|
||||
// Get all blog posts and projects from Appwrite
|
||||
const posts = (await getBlogPosts())
|
||||
.filter(post => !post.draft)
|
||||
|
||||
const projects = (await getCollection("projects"))
|
||||
.filter(post => !post.data.draft)
|
||||
const projects = (await getProjects())
|
||||
.filter(project => !project.draft)
|
||||
|
||||
const data = [...posts, ...projects] as CollectionEntry<"blog">[]
|
||||
// Create unified data array for search - need to convert to proper format expected by Search component
|
||||
const searchData = [
|
||||
...posts.map(post => ({
|
||||
id: post.$id,
|
||||
slug: post.$id,
|
||||
body: post.contentHtml || post.content,
|
||||
collection: "blog",
|
||||
data: {
|
||||
title: post.title,
|
||||
summary: post.summary,
|
||||
date: new Date(post.date),
|
||||
tags: post.tags,
|
||||
draft: post.draft,
|
||||
content: post.contentHtml || post.content
|
||||
},
|
||||
render: async () => ({
|
||||
Content: () => {},
|
||||
headings: [],
|
||||
remarkPluginFrontmatter: {}
|
||||
})
|
||||
})),
|
||||
...projects.map(project => ({
|
||||
id: project.$id,
|
||||
slug: project.$id,
|
||||
body: project.contentHtml || project.content,
|
||||
collection: "projects",
|
||||
data: {
|
||||
title: project.title,
|
||||
summary: project.summary,
|
||||
date: new Date(project.date),
|
||||
tags: project.tags,
|
||||
draft: project.draft,
|
||||
demoUrl: project.demoUrl,
|
||||
repoUrl: project.repoUrl,
|
||||
content: project.contentHtml || project.content
|
||||
},
|
||||
render: async () => ({
|
||||
Content: () => {},
|
||||
headings: [],
|
||||
remarkPluginFrontmatter: {}
|
||||
})
|
||||
}))
|
||||
]
|
||||
---
|
||||
|
||||
<PageLayout title={SEARCH.TITLE} description={SEARCH.DESCRIPTION}>
|
||||
@@ -23,7 +67,7 @@ const data = [...posts, ...projects] as CollectionEntry<"blog">[]
|
||||
</TopLayout>
|
||||
<BottomLayout>
|
||||
<div class="animate">
|
||||
<Search client:load data={data}/>
|
||||
<Search client:load data={searchData}/>
|
||||
</div>
|
||||
</BottomLayout>
|
||||
</PageLayout>
|
||||
</PageLayout>
|
||||
@@ -31,7 +31,7 @@ const work = await getWorkExperiences()
|
||||
})
|
||||
|
||||
function formatWorkDate(input: Date | string) {
|
||||
if (typeof input === "string") return input
|
||||
if (typeof input === "string") input = new Date(input)
|
||||
|
||||
const month = input.toLocaleDateString("en-US", {
|
||||
month: "short",
|
||||
|
||||
@@ -10,6 +10,8 @@ export type BlogPost = Models.Document & {
|
||||
draft: boolean;
|
||||
content: string;
|
||||
image?: string; // File ID for the featured image
|
||||
template: string; // e.g., "default", "feature", "news"
|
||||
featured: boolean;
|
||||
};
|
||||
|
||||
export type Project = Models.Document & {
|
||||
@@ -22,6 +24,8 @@ export type Project = Models.Document & {
|
||||
repoUrl?: string;
|
||||
content: string;
|
||||
image?: string; // File ID for the featured image
|
||||
template: string; // e.g., "default", "feature"
|
||||
featured: boolean;
|
||||
};
|
||||
|
||||
export type WorkExperience = Models.Document & {
|
||||
|
||||
Reference in new issue
Block a user