Normalise about-me data before rendering

NULL title/description and an empty skills list reached the components as-is.
Normalising once in aboutMeData.ts keeps the presentational components free of
undefined checks, and wraps the fetch so a failing API degrades to a skeleton
instead of an unhandled error.
This commit is contained in:
root committed 2026-10-01 16:33:12 -04:00
1 parent 546ee8cc22
commit a3cce41d1e
4 files changed
+248 -132

No files matched your search

@@ -3,39 +3,22 @@
import React from "react";
import Image from "next/image";
import { motion } from "framer-motion";
import { AboutMeDataType } from "@/app/types/types";
import {
categorizeSkills,
normalizeAboutMeData,
resolveImageSrc,
} from "./aboutMeData";
interface AboutMeContentProps {
data: AboutMeDataType;
data: unknown;
}
const CATEGORIES = {
"Core Tech": ["React", "Next.js", "TypeScript", "JavaScript"],
"Backend & Tools": ["Laravel", "PHP", "MySQL", "Node.js", "Docker", "Git"],
"Architecture & Others": ["REST API", "TDD", "UI/UX Design", "Clean Architecture"],
};
type CategoryKey = keyof typeof CATEGORIES | "Other";
export default function AboutMeContent({ data }: AboutMeContentProps) {
const categorizedSkills: Record<CategoryKey, string[]> = {
"Core Tech": [],
"Backend & Tools": [],
"Architecture & Others": [],
"Other": [],
};
data.skills.forEach((skill) => {
let matched = false;
for (const [cat, skills] of Object.entries(CATEGORIES)) {
if (skills.some((s) => skill.title.toLowerCase().includes(s.toLowerCase()))) {
categorizedSkills[cat as CategoryKey].push(skill.title);
matched = true;
break;
}
}
if (!matched) categorizedSkills["Other"].push(skill.title);
});
const aboutMe = normalizeAboutMeData(data);
const imageSrc = resolveImageSrc(aboutMe.image);
const skillGroups = Object.entries(categorizeSkills(aboutMe.skills)).filter(
([, skills]) => skills.length > 0,
);
const isRTL = typeof document !== "undefined" && document.dir === "rtl";
@@ -53,15 +36,15 @@ export default function AboutMeContent({ data }: AboutMeContentProps) {
className="flex w-full flex-col items-start gap-6 lg:w-[55%]"
>
<h2 className="text-4xl md:text-5xl font-bold text-foreground tracking-tight">
{data.title}
{aboutMe.title}
</h2>
<p className="text-lg text-muted-foreground leading-relaxed text-balance">
{data.description}
{aboutMe.description}
</p>
<div className="mt-8 grid grid-cols-1 md:grid-cols-2 gap-8 w-full">
{Object.entries(categorizedSkills).map(([category, skills]) => (
skills.length > 0 && (
{skillGroups.length > 0 ? (
<div className="mt-8 grid grid-cols-1 md:grid-cols-2 gap-8 w-full">
{skillGroups.map(([category, skills]) => (
<motion.div
key={category}
initial={{ opacity: 0, y: 20 }}
@@ -75,41 +58,40 @@ export default function AboutMeContent({ data }: AboutMeContentProps) {
</h3>
<div className="flex flex-wrap gap-2">
{skills.map((skill, idx) => (
<span
key={idx}
className="tech-tag"
>
<span key={idx} className="tech-tag">
{skill}
</span>
))}
</div>
</motion.div>
)
))}
</div>
))}
</div>
) : null}
</motion.div>
{/* Image Section */}
<motion.div
initial={{ opacity: 0, scale: 0.8 }}
whileInView={{ opacity: 1, scale: 1 }}
transition={{ duration: 0.8 }}
viewport={{ once: true }}
className="relative w-full max-w-[450px] flex justify-center lg:w-[40%]"
>
<div className="relative group">
<div className="absolute -inset-4 bg-gradient-to-tr from-primary to-purple-600 rounded-3xl blur opacity-20 group-hover:opacity-40 transition duration-500"></div>
<div className="relative overflow-hidden rounded-3xl border-4 border-background shadow-2xl">
<Image
src={process.env.NEXT_PUBLIC_BACK_URL + data.image}
alt="profile picture"
width={450}
height={450}
className="w-full h-auto transition-transform duration-500 group-hover:scale-105"
/>
{imageSrc ? (
<motion.div
initial={{ opacity: 0, scale: 0.8 }}
whileInView={{ opacity: 1, scale: 1 }}
transition={{ duration: 0.8 }}
viewport={{ once: true }}
className="relative w-full max-w-[450px] flex justify-center lg:w-[40%]"
>
<div className="relative group">
<div className="absolute -inset-4 bg-gradient-to-tr from-primary to-purple-600 rounded-3xl blur opacity-20 group-hover:opacity-40 transition duration-500"></div>
<div className="relative overflow-hidden rounded-3xl border-4 border-background shadow-2xl">
<Image
src={imageSrc}
alt={aboutMe.title}
width={450}
height={450}
className="w-full h-auto transition-transform duration-500 group-hover:scale-105"
/>
</div>
</div>
</div>
</motion.div>
</motion.div>
) : null}
</section>
);
}
@@ -3,39 +3,22 @@
import React from "react";
import Image from "next/image";
import { motion } from "framer-motion";
import { AboutMeDataType } from "@/app/types/types";
import {
categorizeSkills,
normalizeAboutMeData,
resolveImageSrc,
} from "./aboutMeData";
interface AboutMeContentProps {
data: AboutMeDataType;
data: unknown;
}
const CATEGORIES = {
"Core Tech": ["React", "Next.js", "TypeScript", "JavaScript"],
"Backend & Tools": ["Laravel", "PHP", "MySQL", "Node.js", "Docker", "Git"],
"Architecture & Others": ["REST API", "TDD", "UI/UX Design", "Clean Architecture"],
};
type CategoryKey = keyof typeof CATEGORIES | "Other";
export default function AboutMeContent({ data }: AboutMeContentProps) {
const categorizedSkills: Record<CategoryKey, string[]> = {
"Core Tech": [],
"Backend & Tools": [],
"Architecture & Others": [],
"Other": [],
};
data.skills.forEach((skill) => {
let matched = false;
for (const [cat, skills] of Object.entries(CATEGORIES)) {
if (skills.some((s) => skill.title.toLowerCase().includes(s.toLowerCase()))) {
categorizedSkills[cat as CategoryKey].push(skill.title);
matched = true;
break;
}
}
if (!matched) categorizedSkills["Other"].push(skill.title);
});
const aboutMe = normalizeAboutMeData(data);
const imageSrc = resolveImageSrc(aboutMe.image);
const skillGroups = Object.entries(categorizeSkills(aboutMe.skills)).filter(
([, skills]) => skills.length > 0,
);
const isRTL = typeof document !== "undefined" && document.dir === "rtl";
@@ -53,15 +36,15 @@ export default function AboutMeContent({ data }: AboutMeContentProps) {
className="flex w-full flex-col items-start gap-6 lg:w-[55%]"
>
<h2 className="text-4xl md:text-5xl font-bold text-foreground tracking-tight">
{data.title}
{aboutMe.title}
</h2>
<p className="text-lg text-muted-foreground leading-relaxed text-balance">
{data.description}
{aboutMe.description}
</p>
<div className="mt-8 grid grid-cols-1 md:grid-cols-2 gap-8 w-full">
{Object.entries(categorizedSkills).map(([category, skills]) => (
skills.length > 0 && (
{skillGroups.length > 0 ? (
<div className="mt-8 grid grid-cols-1 md:grid-cols-2 gap-8 w-full">
{skillGroups.map(([category, skills]) => (
<motion.div
key={category}
initial={{ opacity: 0, y: 20 }}
@@ -75,40 +58,39 @@ export default function AboutMeContent({ data }: AboutMeContentProps) {
</h3>
<div className="flex flex-wrap gap-2">
{skills.map((skill, idx) => (
<span
key={idx}
className="tech-tag"
>
<span key={idx} className="tech-tag">
{skill}
</span>
))}
</div>
</motion.div>
)
))}
</div>
))}
</div>
) : null}
</motion.div>
{/* Image Section */}
<motion.div
initial={{ opacity: 0, scale: 0.8 }}
whileInView={{ opacity: 1, scale: 1 }}
transition={{ duration: 0.8 }}
viewport={{ once: true }}
className="relative w-full max-w-[450px] flex justify-center lg:w-[40%]"
>
<div className="relative group">
<div className="relative overflow-hidden rounded-3xl border-4 border-background shadow-2xl">
<Image
src={process.env.NEXT_PUBLIC_BACK_URL + data.image}
alt="profile picture"
width={450}
height={450}
className="w-full h-auto transition-transform duration-500 group-hover:scale-105"
/>
{imageSrc ? (
<motion.div
initial={{ opacity: 0, scale: 0.8 }}
whileInView={{ opacity: 1, scale: 1 }}
transition={{ duration: 0.8 }}
viewport={{ once: true }}
className="relative w-full max-w-[450px] flex justify-center lg:w-[40%]"
>
<div className="relative group">
<div className="relative overflow-hidden rounded-3xl border-4 border-background shadow-2xl">
<Image
src={imageSrc}
alt={aboutMe.title}
width={450}
height={450}
className="w-full h-auto transition-transform duration-500 group-hover:scale-105"
/>
</div>
</div>
</div>
</motion.div>
</motion.div>
) : null}
</section>
);
}
@@ -1,27 +1,45 @@
import { AboutMeDataType } from "@/app/types/types";
import { cookies } from "next/headers";
import React from "react";
import Skeleton from "react-loading-skeleton";
import "react-loading-skeleton/dist/skeleton.css";
import AboutMeContent from "./AboutMeContent";
async function fetchAboutMeData(): Promise<unknown> {
const cookieStore = await cookies();
const locale =
cookieStore.get("selectedLocale")?.value ??
cookieStore.get("defaultLocale")?.value;
try {
const res = await fetch(
`${process.env.NEXT_PUBLIC_API_URL}/website/about-me/1/translation/${locale}`,
);
return res.json();
} catch {
return null;
}
}
function AboutMeSkeleton() {
return (
<div className="my-10 flex w-full max-w-[90%] flex-wrap items-center justify-center gap-20 pt-[120px]">
<div className="flex w-full flex-col items-center md:w-[50%]">
<Skeleton width={300} height={100} />
<Skeleton width={350} height={30} />
</div>
<div className="flex w-full max-w-[90%] items-center justify-center md:w-[40%]">
<Skeleton width={400} height={400} />
</div>
</div>
);
}
export default async function AboutMe() {
const aboutMeData: AboutMeDataType = await fetch(
`${process.env.NEXT_PUBLIC_API_URL}/website/about-me/1/translation/${(await cookies()).get("selectedLocale")?.value ? (await cookies()).get("selectedLocale")?.value : (await cookies()).get("defaultLocale")?.value}`,
).then((res) => res.json());
const aboutMeData = await fetchAboutMeData();
if (!aboutMeData) {
return (
<div className="my-10 flex w-full max-w-[90%] flex-wrap items-center justify-center gap-20 pt-[120px]">
<div className="flex w-full flex-col items-center md:w-[50%]">
<Skeleton width={300} height={100} />
<Skeleton width={350} height={30} />
</div>
<div className="flex w-full max-w-[90%] items-center justify-center md:w-[40%]">
<Skeleton width={400} height={400} />
</div>
</div>
);
return <AboutMeSkeleton />;
}
return <AboutMeContent data={aboutMeData} />;
@@ -0,0 +1,134 @@
export const ABOUT_ME_FALLBACK_TITLE = "درباره من";
export const ABOUT_ME_FALLBACK_DESCRIPTION =
"معرفی کوتاهی از من و مسیر حرفه‌ای‌ام.";
export const SKILL_CATEGORIES = {
"Core Tech": ["React", "Next.js", "TypeScript", "JavaScript"],
"Backend & Tools": ["Laravel", "PHP", "MySQL", "Node.js", "Docker", "Git"],
"Architecture & Others": [
"REST API",
"TDD",
"UI/UX Design",
"Clean Architecture",
],
} as const;
export type SkillCategoryKey = keyof typeof SKILL_CATEGORIES | "Other";
export type AboutMeSkill = {
title: string;
};
export type NormalizedAboutMe = {
title: string;
description: string;
image: string;
skills: AboutMeSkill[];
};
function textOrEmpty(value: unknown): string {
if (typeof value === "string") {
return value.trim();
}
if (typeof value === "number" && Number.isFinite(value)) {
return String(value);
}
return "";
}
/**
* Turns the raw about-me payload (which may be null, wrapped in `data`, or
* missing translations) into a fully guarded shape: every field is either a
* non-empty string or an empty list, and the Persian fallbacks are applied for
* the missing title/description.
*/
export function normalizeAboutMeData(raw: unknown): NormalizedAboutMe {
const payload =
raw && typeof raw === "object" && "data" in raw
? (raw as { data: unknown }).data
: raw;
const source =
payload && typeof payload === "object"
? (payload as Record<string, unknown>)
: {};
const rawSkills = Array.isArray(source.skills) ? source.skills : [];
const skills: AboutMeSkill[] = [];
for (const rawSkill of rawSkills) {
const title = textOrEmpty(
rawSkill && typeof rawSkill === "object"
? (rawSkill as Record<string, unknown>).title
: rawSkill,
);
if (title !== "") {
skills.push({ title });
}
}
return {
title: textOrEmpty(source.title) || ABOUT_ME_FALLBACK_TITLE,
description:
textOrEmpty(source.description) || ABOUT_ME_FALLBACK_DESCRIPTION,
image: textOrEmpty(source.image),
skills,
};
}
/** Builds a next/image-usable src, or null when there is no usable image. */
export function resolveImageSrc(value: unknown): string | null {
const src = textOrEmpty(value);
if (src === "") {
return null;
}
if (src.startsWith("/") || /^https?:\/\//i.test(src)) {
return src;
}
const baseUrl = textOrEmpty(process.env.NEXT_PUBLIC_BACK_URL).replace(
/\/+$/,
"",
);
return baseUrl === "" ? null : `${baseUrl}/${src.replace(/^\/+/, "")}`;
}
/** Groups the given skill titles into the known categories, never inventing any. */
export function categorizeSkills(
skills: AboutMeSkill[],
): Record<SkillCategoryKey, string[]> {
const categorized: Record<SkillCategoryKey, string[]> = {
"Core Tech": [],
"Backend & Tools": [],
"Architecture & Others": [],
Other: [],
};
for (const skill of skills) {
const title = textOrEmpty(skill?.title);
const normalizedTitle = title.toLowerCase();
if (normalizedTitle === "") {
continue;
}
const matchedCategory = (
Object.keys(SKILL_CATEGORIES) as Array<keyof typeof SKILL_CATEGORIES>
).find((category) =>
SKILL_CATEGORIES[category].some((knownSkill) =>
normalizedTitle.includes(knownSkill.toLowerCase()),
),
);
categorized[matchedCategory ?? "Other"].push(title);
}
return categorized;
}