Initial commit
This commit is contained in:
129
src/lib/api/blog.ts
Normal file
129
src/lib/api/blog.ts
Normal file
@@ -0,0 +1,129 @@
|
||||
type BlogPost = {
|
||||
id: string;
|
||||
slug?: string;
|
||||
category: string;
|
||||
title: string;
|
||||
excerpt: string;
|
||||
content?: string;
|
||||
imageSrc: string;
|
||||
imageAlt?: string;
|
||||
authorName: string;
|
||||
authorAvatar: string;
|
||||
date: string;
|
||||
onBlogClick?: () => void;
|
||||
};
|
||||
|
||||
const defaultPosts: BlogPost[] = [
|
||||
{
|
||||
id: "1",
|
||||
category: "Design",
|
||||
title: "UX review presentations",
|
||||
excerpt: "How do you create compelling presentations that wow your colleagues and impress your managers?",
|
||||
imageSrc: "https://storage.googleapis.com/webild/default/placeholders/placeholder-1.webp",
|
||||
imageAlt: "Abstract design with purple and silver tones",
|
||||
authorName: "Olivia Rhye",
|
||||
authorAvatar: "https://storage.googleapis.com/webild/default/placeholders/placeholder-1.webp",
|
||||
date: "20 Jan 2025",
|
||||
},
|
||||
{
|
||||
id: "2",
|
||||
category: "Development",
|
||||
title: "Building scalable applications",
|
||||
excerpt: "Learn the best practices for building applications that can handle millions of users.",
|
||||
imageSrc: "https://storage.googleapis.com/webild/default/placeholders/placeholder-2.webp",
|
||||
imageAlt: "Development workspace",
|
||||
authorName: "John Smith",
|
||||
authorAvatar: "https://storage.googleapis.com/webild/default/placeholders/placeholder-2.webp",
|
||||
date: "18 Jan 2025",
|
||||
},
|
||||
{
|
||||
id: "3",
|
||||
category: "Marketing",
|
||||
title: "Content strategy essentials",
|
||||
excerpt: "Discover how to create a content strategy that drives engagement and conversions.",
|
||||
imageSrc: "https://storage.googleapis.com/webild/default/placeholders/placeholder-3.webp",
|
||||
imageAlt: "Marketing strategy board",
|
||||
authorName: "Sarah Johnson",
|
||||
authorAvatar: "https://storage.googleapis.com/webild/default/placeholders/placeholder-3.webp",
|
||||
date: "15 Jan 2025",
|
||||
},
|
||||
{
|
||||
id: "4",
|
||||
category: "Product",
|
||||
title: "Product management 101",
|
||||
excerpt: "Everything you need to know to become an effective product manager in 2025.",
|
||||
imageSrc: "https://storage.googleapis.com/webild/default/placeholders/placeholder-1.webp",
|
||||
imageAlt: "Product planning session",
|
||||
authorName: "Mike Davis",
|
||||
authorAvatar: "https://storage.googleapis.com/webild/default/placeholders/placeholder-1.webp",
|
||||
date: "12 Jan 2025",
|
||||
},
|
||||
];
|
||||
|
||||
const htmlToExcerpt = (html: string | undefined, maxLength = 160): string => {
|
||||
if (!html) return "";
|
||||
const text = html
|
||||
.replace(/<[^>]*>/g, " ")
|
||||
.replace(/ /gi, " ")
|
||||
.replace(/&/gi, "&")
|
||||
.replace(/\s+/g, " ")
|
||||
.trim();
|
||||
return text.length <= maxLength ? text : `${text.slice(0, maxLength).trimEnd()}…`;
|
||||
};
|
||||
|
||||
const fetchBlogPosts = async (): Promise<BlogPost[]> => {
|
||||
const apiUrl = import.meta.env.VITE_API_URL;
|
||||
const projectId = import.meta.env.VITE_PROJECT_ID;
|
||||
|
||||
if (!apiUrl || !projectId) {
|
||||
console.warn("VITE_API_URL or VITE_PROJECT_ID not configured");
|
||||
return [];
|
||||
}
|
||||
|
||||
try {
|
||||
const url = `${apiUrl}/posts/${projectId}?status=published`;
|
||||
const response = await fetch(url, {
|
||||
method: "GET",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
console.warn(`API request failed with status ${response.status}`);
|
||||
return [];
|
||||
}
|
||||
|
||||
const resp = await response.json();
|
||||
const data = resp.data;
|
||||
|
||||
if (!Array.isArray(data) || data.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return data.map((post: Record<string, unknown>) => ({
|
||||
id: (post.id as string) || String(Math.random()),
|
||||
slug: (post.slug as string) || (post.id as string) || undefined,
|
||||
category: (post.category as string) || "General",
|
||||
title: (post.title as string) || "Untitled",
|
||||
excerpt: (post.excerpt as string) || htmlToExcerpt(post.content as string),
|
||||
content: (post.content as string) || "",
|
||||
imageSrc: (post.imageUrl as string) || "https://storage.googleapis.com/webild/default/placeholders/placeholder-1.webp",
|
||||
imageAlt: (post.imageAlt as string) || (post.title as string) || "",
|
||||
authorName: (post.author as Record<string, string>)?.name || "Anonymous",
|
||||
authorAvatar: (post.author as Record<string, string>)?.avatar || "https://storage.googleapis.com/webild/default/placeholders/placeholder-1.webp",
|
||||
date: (post.date as string) || (post.createdAt as string) || new Date().toLocaleDateString("en-GB", { day: "numeric", month: "short", year: "numeric" }),
|
||||
}));
|
||||
} catch (error) {
|
||||
console.error("Error fetching posts:", error);
|
||||
return [];
|
||||
}
|
||||
};
|
||||
|
||||
const fetchBlogPost = async (slugOrId: string): Promise<BlogPost | null> => {
|
||||
if (!slugOrId) return null;
|
||||
const posts = await fetchBlogPosts();
|
||||
return posts.find((p) => p.slug === slugOrId || p.id === slugOrId) ?? null;
|
||||
};
|
||||
|
||||
export { fetchBlogPosts, fetchBlogPost, defaultPosts, type BlogPost };
|
||||
64
src/lib/api/email.ts
Normal file
64
src/lib/api/email.ts
Normal file
@@ -0,0 +1,64 @@
|
||||
type ContactEmailData = {
|
||||
formData?: Record<string, string>;
|
||||
message?: string;
|
||||
email?: string;
|
||||
};
|
||||
|
||||
const createMessage = (data: ContactEmailData): string => {
|
||||
if (data.message && data.message.trim()) {
|
||||
return data.message.trim();
|
||||
}
|
||||
|
||||
if (data.formData && Object.keys(data.formData).length > 0) {
|
||||
if (data.formData.message && data.formData.message.trim()) {
|
||||
return data.formData.message.trim();
|
||||
}
|
||||
|
||||
const lines: string[] = [];
|
||||
Object.entries(data.formData).forEach(([key, value]) => {
|
||||
if (value && value.trim()) {
|
||||
const fieldName = key.charAt(0).toUpperCase() + key.slice(1).replace(/([A-Z])/g, " $1");
|
||||
lines.push(`${fieldName}: ${value.trim()}`);
|
||||
}
|
||||
});
|
||||
|
||||
if (lines.length > 0) {
|
||||
return lines.join("\n\n");
|
||||
}
|
||||
}
|
||||
|
||||
return "A new contact form submission has been received.";
|
||||
};
|
||||
|
||||
const sendContactEmail = async (data: ContactEmailData): Promise<Response> => {
|
||||
const message = createMessage(data);
|
||||
const fromEmail = data.formData?.email || data.email || "noreply@example.com";
|
||||
|
||||
const apiUrl = import.meta.env.VITE_API_URL;
|
||||
const projectId = import.meta.env.VITE_PROJECT_ID;
|
||||
|
||||
if (!apiUrl || !projectId) {
|
||||
throw new Error("VITE_API_URL and VITE_PROJECT_ID must be set");
|
||||
}
|
||||
|
||||
const response = await fetch(`${apiUrl}/emails/projects/${projectId}/sendMail`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
message,
|
||||
fromEmail,
|
||||
formData: data.formData,
|
||||
}),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const error = await response.json().catch(() => ({ error: "Failed to send email" }));
|
||||
throw new Error(error.error || "Failed to send email");
|
||||
}
|
||||
|
||||
return response;
|
||||
};
|
||||
|
||||
export { sendContactEmail, type ContactEmailData };
|
||||
222
src/lib/api/product.ts
Normal file
222
src/lib/api/product.ts
Normal file
@@ -0,0 +1,222 @@
|
||||
type Product = {
|
||||
id: string;
|
||||
name: string;
|
||||
price: string;
|
||||
imageSrc: string;
|
||||
imageAlt?: string;
|
||||
images?: string[];
|
||||
brand?: string;
|
||||
variant?: string;
|
||||
rating?: number;
|
||||
reviewCount?: string;
|
||||
description?: string;
|
||||
priceId?: string;
|
||||
metadata?: Record<string, string | number | undefined>;
|
||||
onFavorite?: () => void;
|
||||
onProductClick?: () => void;
|
||||
isFavorited?: boolean;
|
||||
};
|
||||
|
||||
const defaultProducts: Product[] = [
|
||||
{
|
||||
id: "1",
|
||||
name: "Classic White Sneakers",
|
||||
price: "$129",
|
||||
brand: "Nike",
|
||||
variant: "White / Size 42",
|
||||
rating: 4.5,
|
||||
reviewCount: "128",
|
||||
imageSrc: "https://storage.googleapis.com/webild/default/placeholders/placeholder-1.webp",
|
||||
imageAlt: "Classic white sneakers",
|
||||
},
|
||||
{
|
||||
id: "2",
|
||||
name: "Leather Crossbody Bag",
|
||||
price: "$89",
|
||||
brand: "Coach",
|
||||
variant: "Brown / Medium",
|
||||
rating: 4.8,
|
||||
reviewCount: "256",
|
||||
imageSrc: "https://storage.googleapis.com/webild/default/placeholders/placeholder-2.webp",
|
||||
imageAlt: "Brown leather crossbody bag",
|
||||
},
|
||||
{
|
||||
id: "3",
|
||||
name: "Wireless Headphones",
|
||||
price: "$199",
|
||||
brand: "Sony",
|
||||
variant: "Black",
|
||||
rating: 4.7,
|
||||
reviewCount: "512",
|
||||
imageSrc: "https://storage.googleapis.com/webild/default/placeholders/placeholder-3.webp",
|
||||
imageAlt: "Black wireless headphones",
|
||||
},
|
||||
{
|
||||
id: "4",
|
||||
name: "Minimalist Watch",
|
||||
price: "$249",
|
||||
brand: "Fossil",
|
||||
variant: "Silver / 40mm",
|
||||
rating: 4.6,
|
||||
reviewCount: "89",
|
||||
imageSrc: "https://storage.googleapis.com/webild/default/placeholders/placeholder-1.webp",
|
||||
imageAlt: "Silver minimalist watch",
|
||||
},
|
||||
];
|
||||
|
||||
const formatPrice = (amount: number, currency: string): string => {
|
||||
const formatter = new Intl.NumberFormat("en-US", {
|
||||
style: "currency",
|
||||
currency: currency.toUpperCase(),
|
||||
minimumFractionDigits: 0,
|
||||
maximumFractionDigits: 2,
|
||||
});
|
||||
return formatter.format(amount / 100);
|
||||
};
|
||||
|
||||
const fetchProducts = async (): Promise<Product[]> => {
|
||||
const apiUrl = import.meta.env.VITE_API_URL;
|
||||
const projectId = import.meta.env.VITE_PROJECT_ID;
|
||||
|
||||
if (!apiUrl || !projectId) {
|
||||
return [];
|
||||
}
|
||||
|
||||
try {
|
||||
const url = `${apiUrl}/stripe/project/products?projectId=${projectId}&expandDefaultPrice=true`;
|
||||
const response = await fetch(url, {
|
||||
method: "GET",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const resp = await response.json();
|
||||
const data = resp.data.data || resp.data;
|
||||
|
||||
if (!Array.isArray(data) || data.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return data.map((product: Record<string, unknown>) => {
|
||||
const metadata: Record<string, string | number | undefined> = {};
|
||||
const productMetadata = product.metadata as Record<string, unknown> | undefined;
|
||||
if (productMetadata && typeof productMetadata === "object") {
|
||||
Object.keys(productMetadata).forEach((key) => {
|
||||
const value = productMetadata[key];
|
||||
if (value !== null && value !== undefined) {
|
||||
const numValue = parseFloat(String(value));
|
||||
metadata[key] = isNaN(numValue) ? String(value) : numValue;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
const images = product.images as string[] | undefined;
|
||||
const imageSrc = images?.[0] || (product.imageSrc as string) || "https://storage.googleapis.com/webild/default/placeholders/placeholder-1.webp";
|
||||
const imageAlt = (product.imageAlt as string) || (product.name as string) || "";
|
||||
const finalImages = images && Array.isArray(images) && images.length > 0 ? images : [imageSrc];
|
||||
|
||||
const defaultPrice = product.default_price as Record<string, unknown> | undefined;
|
||||
|
||||
return {
|
||||
id: (product.id as string) || String(Math.random()),
|
||||
name: (product.name as string) || "Untitled Product",
|
||||
description: (product.description as string) || "",
|
||||
price: defaultPrice?.unit_amount
|
||||
? formatPrice(defaultPrice.unit_amount as number, (defaultPrice.currency as string) || "usd")
|
||||
: (product.price as string) || "$0",
|
||||
priceId: (defaultPrice?.id as string) || (product.priceId as string),
|
||||
imageSrc,
|
||||
imageAlt,
|
||||
images: finalImages,
|
||||
brand: (productMetadata?.brand as string) || (product.brand as string) || "",
|
||||
variant: (productMetadata?.variant as string) || (product.variant as string) || "",
|
||||
rating: productMetadata?.rating ? parseFloat(String(productMetadata.rating)) : undefined,
|
||||
reviewCount: (productMetadata?.reviewCount as string) || undefined,
|
||||
metadata: Object.keys(metadata).length > 0 ? metadata : undefined,
|
||||
};
|
||||
});
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
};
|
||||
|
||||
const fetchProduct = async (productId: string): Promise<Product | null> => {
|
||||
const apiUrl = import.meta.env.VITE_API_URL;
|
||||
const projectId = import.meta.env.VITE_PROJECT_ID;
|
||||
|
||||
if (!apiUrl || !projectId) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
const url = `${apiUrl}/stripe/project/products/${productId}?projectId=${projectId}&expandDefaultPrice=true`;
|
||||
const response = await fetch(url, {
|
||||
method: "GET",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const resp = await response.json();
|
||||
const product = resp.data?.data || resp.data || resp;
|
||||
|
||||
if (!product || typeof product !== "object") {
|
||||
return null;
|
||||
}
|
||||
|
||||
const metadata: Record<string, string | number | undefined> = {};
|
||||
const productMetadata = product.metadata as Record<string, unknown> | undefined;
|
||||
if (productMetadata && typeof productMetadata === "object") {
|
||||
Object.keys(productMetadata).forEach((key) => {
|
||||
const value = productMetadata[key];
|
||||
if (value !== null && value !== undefined && value !== "") {
|
||||
const numValue = parseFloat(String(value));
|
||||
metadata[key] = isNaN(numValue) ? String(value) : numValue;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
const defaultPrice = product.default_price as Record<string, unknown> | undefined;
|
||||
let priceValue = product.price as string | undefined;
|
||||
if (!priceValue && defaultPrice?.unit_amount) {
|
||||
priceValue = formatPrice(defaultPrice.unit_amount as number, (defaultPrice.currency as string) || "usd");
|
||||
}
|
||||
if (!priceValue) {
|
||||
priceValue = "$0";
|
||||
}
|
||||
|
||||
const images = product.images as string[] | undefined;
|
||||
const imageSrc = images?.[0] || (product.imageSrc as string) || "https://storage.googleapis.com/webild/default/placeholders/placeholder-1.webp";
|
||||
const imageAlt = (product.imageAlt as string) || (product.name as string) || "";
|
||||
const finalImages = images && Array.isArray(images) && images.length > 0 ? images : [imageSrc];
|
||||
|
||||
return {
|
||||
id: (product.id as string) || String(Math.random()),
|
||||
name: (product.name as string) || "Untitled Product",
|
||||
description: (product.description as string) || "",
|
||||
price: priceValue,
|
||||
priceId: (defaultPrice?.id as string) || (product.priceId as string),
|
||||
imageSrc,
|
||||
imageAlt,
|
||||
images: finalImages,
|
||||
brand: (productMetadata?.brand as string) || (product.brand as string) || "",
|
||||
variant: (productMetadata?.variant as string) || (product.variant as string) || "",
|
||||
rating: productMetadata?.rating ? parseFloat(String(productMetadata.rating)) : undefined,
|
||||
reviewCount: (productMetadata?.reviewCount as string) || undefined,
|
||||
metadata: Object.keys(metadata).length > 0 ? metadata : undefined,
|
||||
};
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
export { fetchProducts, fetchProduct, defaultProducts, formatPrice, type Product };
|
||||
Reference in New Issue
Block a user