feat(media): implement nextjs media proxy API routes (/api/uploads & /api/media) with server-side caching and streaming
This commit is contained in:
1 parent
d9c693c41b
commit
fa1a35c835
19 files changed
+13806
-13030
No files matched your search
@@ -0,0 +1,113 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
export async function GET(
|
||||
request: NextRequest,
|
||||
{ params }: { params: Promise<{ path: string[] }> }
|
||||
) {
|
||||
try {
|
||||
const { path } = await params;
|
||||
if (!path || path.length === 0) {
|
||||
return new NextResponse('Bad Request: Missing file path', { status: 400 });
|
||||
}
|
||||
|
||||
const filePath = path.map(segment => encodeURIComponent(segment)).join('/');
|
||||
const backendBase = (
|
||||
process.env.INTERNAL_API_URL ||
|
||||
process.env.NEXT_PUBLIC_API_URL ||
|
||||
'http://127.0.0.1:4001'
|
||||
).replace(/\/api\/?$/, '');
|
||||
|
||||
const targetUrl = `${backendBase}/uploads/${filePath}`;
|
||||
|
||||
const forwardedHeaders: HeadersInit = {};
|
||||
const rangeHeader = request.headers.get('range');
|
||||
if (rangeHeader) forwardedHeaders['range'] = rangeHeader;
|
||||
const ifNoneMatch = request.headers.get('if-none-match');
|
||||
if (ifNoneMatch) forwardedHeaders['if-none-match'] = ifNoneMatch;
|
||||
const ifModifiedSince = request.headers.get('if-modified-since');
|
||||
if (ifModifiedSince) forwardedHeaders['if-modified-since'] = ifModifiedSince;
|
||||
|
||||
const backendRes = await fetch(targetUrl, {
|
||||
method: 'GET',
|
||||
headers: forwardedHeaders,
|
||||
cache: 'no-store',
|
||||
});
|
||||
|
||||
if (!backendRes.ok && backendRes.status !== 304 && backendRes.status !== 206) {
|
||||
return new NextResponse(`Media not found or error from upstream (${backendRes.status})`, {
|
||||
status: backendRes.status,
|
||||
});
|
||||
}
|
||||
|
||||
const responseHeaders = new Headers();
|
||||
const contentType = backendRes.headers.get('content-type') || 'application/octet-stream';
|
||||
responseHeaders.set('Content-Type', contentType);
|
||||
|
||||
const contentLength = backendRes.headers.get('content-length');
|
||||
if (contentLength) responseHeaders.set('Content-Length', contentLength);
|
||||
|
||||
const contentRange = backendRes.headers.get('content-range');
|
||||
if (contentRange) responseHeaders.set('Content-Range', contentRange);
|
||||
|
||||
const acceptRanges = backendRes.headers.get('accept-ranges') || 'bytes';
|
||||
responseHeaders.set('Accept-Ranges', acceptRanges);
|
||||
|
||||
const etag = backendRes.headers.get('etag');
|
||||
if (etag) responseHeaders.set('ETag', etag);
|
||||
|
||||
const lastModified = backendRes.headers.get('last-modified');
|
||||
if (lastModified) responseHeaders.set('Last-Modified', lastModified);
|
||||
|
||||
responseHeaders.set('Cache-Control', 'public, max-age=31536000, s-maxage=31536000, immutable');
|
||||
responseHeaders.set('X-Content-Type-Options', 'nosniff');
|
||||
|
||||
return new Response(backendRes.body, {
|
||||
status: backendRes.status,
|
||||
statusText: backendRes.statusText,
|
||||
headers: responseHeaders,
|
||||
});
|
||||
} catch (err: unknown) {
|
||||
console.error('[Media Proxy Error]', err);
|
||||
return new NextResponse('Internal Media Proxy Error', { status: 502 });
|
||||
}
|
||||
}
|
||||
|
||||
export async function HEAD(
|
||||
request: NextRequest,
|
||||
{ params }: { params: Promise<{ path: string[] }> }
|
||||
) {
|
||||
try {
|
||||
const { path } = await params;
|
||||
if (!path || path.length === 0) {
|
||||
return new NextResponse(null, { status: 400 });
|
||||
}
|
||||
|
||||
const filePath = path.map(segment => encodeURIComponent(segment)).join('/');
|
||||
const backendBase = (
|
||||
process.env.INTERNAL_API_URL ||
|
||||
process.env.NEXT_PUBLIC_API_URL ||
|
||||
'http://127.0.0.1:4001'
|
||||
).replace(/\/api\/?$/, '');
|
||||
|
||||
const targetUrl = `${backendBase}/uploads/${filePath}`;
|
||||
const backendRes = await fetch(targetUrl, { method: 'HEAD', cache: 'no-store' });
|
||||
|
||||
const responseHeaders = new Headers();
|
||||
const contentType = backendRes.headers.get('content-type') || 'application/octet-stream';
|
||||
responseHeaders.set('Content-Type', contentType);
|
||||
const contentLength = backendRes.headers.get('content-length');
|
||||
if (contentLength) responseHeaders.set('Content-Length', contentLength);
|
||||
responseHeaders.set('Accept-Ranges', 'bytes');
|
||||
responseHeaders.set('Cache-Control', 'public, max-age=31536000, s-maxage=31536000, immutable');
|
||||
|
||||
return new NextResponse(null, {
|
||||
status: backendRes.status,
|
||||
headers: responseHeaders,
|
||||
});
|
||||
} catch (err: unknown) {
|
||||
console.error('[Media Proxy HEAD Error]', err);
|
||||
return new NextResponse(null, { status: 502 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
export async function GET(
|
||||
request: NextRequest,
|
||||
{ params }: { params: Promise<{ path: string[] }> }
|
||||
) {
|
||||
try {
|
||||
const { path } = await params;
|
||||
if (!path || path.length === 0) {
|
||||
return new NextResponse('Bad Request: Missing file path', { status: 400 });
|
||||
}
|
||||
|
||||
const filePath = path.map(segment => encodeURIComponent(segment)).join('/');
|
||||
const backendBase = (
|
||||
process.env.INTERNAL_API_URL ||
|
||||
process.env.NEXT_PUBLIC_API_URL ||
|
||||
'http://127.0.0.1:4001'
|
||||
).replace(/\/api\/?$/, '');
|
||||
|
||||
const targetUrl = `${backendBase}/uploads/${filePath}`;
|
||||
|
||||
// Forward streaming/caching headers from client to backend
|
||||
const forwardedHeaders: HeadersInit = {};
|
||||
const rangeHeader = request.headers.get('range');
|
||||
if (rangeHeader) {
|
||||
forwardedHeaders['range'] = rangeHeader;
|
||||
}
|
||||
const ifNoneMatch = request.headers.get('if-none-match');
|
||||
if (ifNoneMatch) {
|
||||
forwardedHeaders['if-none-match'] = ifNoneMatch;
|
||||
}
|
||||
const ifModifiedSince = request.headers.get('if-modified-since');
|
||||
if (ifModifiedSince) {
|
||||
forwardedHeaders['if-modified-since'] = ifModifiedSince;
|
||||
}
|
||||
|
||||
const backendRes = await fetch(targetUrl, {
|
||||
method: 'GET',
|
||||
headers: forwardedHeaders,
|
||||
cache: 'no-store', // Always stream directly or use Next.js response headers
|
||||
});
|
||||
|
||||
if (!backendRes.ok && backendRes.status !== 304 && backendRes.status !== 206) {
|
||||
return new NextResponse(`Media not found or error from upstream (${backendRes.status})`, {
|
||||
status: backendRes.status,
|
||||
});
|
||||
}
|
||||
|
||||
// Build response headers with long-term caching and media streaming support
|
||||
const responseHeaders = new Headers();
|
||||
|
||||
// Forward essential media headers
|
||||
const contentType = backendRes.headers.get('content-type') || 'application/octet-stream';
|
||||
responseHeaders.set('Content-Type', contentType);
|
||||
|
||||
const contentLength = backendRes.headers.get('content-length');
|
||||
if (contentLength) {
|
||||
responseHeaders.set('Content-Length', contentLength);
|
||||
}
|
||||
|
||||
const contentRange = backendRes.headers.get('content-range');
|
||||
if (contentRange) {
|
||||
responseHeaders.set('Content-Range', contentRange);
|
||||
}
|
||||
|
||||
const acceptRanges = backendRes.headers.get('accept-ranges') || 'bytes';
|
||||
responseHeaders.set('Accept-Ranges', acceptRanges);
|
||||
|
||||
const etag = backendRes.headers.get('etag');
|
||||
if (etag) {
|
||||
responseHeaders.set('ETag', etag);
|
||||
}
|
||||
|
||||
const lastModified = backendRes.headers.get('last-modified');
|
||||
if (lastModified) {
|
||||
responseHeaders.set('Last-Modified', lastModified);
|
||||
}
|
||||
|
||||
// Set aggressive caching for static media (1 year with immutable)
|
||||
responseHeaders.set('Cache-Control', 'public, max-age=31536000, s-maxage=31536000, immutable');
|
||||
responseHeaders.set('X-Content-Type-Options', 'nosniff');
|
||||
|
||||
return new Response(backendRes.body, {
|
||||
status: backendRes.status,
|
||||
statusText: backendRes.statusText,
|
||||
headers: responseHeaders,
|
||||
});
|
||||
} catch (err: unknown) {
|
||||
console.error('[Media Proxy Error]', err);
|
||||
return new NextResponse('Internal Media Proxy Error', { status: 502 });
|
||||
}
|
||||
}
|
||||
|
||||
export async function HEAD(
|
||||
request: NextRequest,
|
||||
{ params }: { params: Promise<{ path: string[] }> }
|
||||
) {
|
||||
try {
|
||||
const { path } = await params;
|
||||
if (!path || path.length === 0) {
|
||||
return new NextResponse(null, { status: 400 });
|
||||
}
|
||||
|
||||
const filePath = path.map(segment => encodeURIComponent(segment)).join('/');
|
||||
const backendBase = (
|
||||
process.env.INTERNAL_API_URL ||
|
||||
process.env.NEXT_PUBLIC_API_URL ||
|
||||
'http://127.0.0.1:4001'
|
||||
).replace(/\/api\/?$/, '');
|
||||
|
||||
const targetUrl = `${backendBase}/uploads/${filePath}`;
|
||||
const backendRes = await fetch(targetUrl, { method: 'HEAD', cache: 'no-store' });
|
||||
|
||||
const responseHeaders = new Headers();
|
||||
const contentType = backendRes.headers.get('content-type') || 'application/octet-stream';
|
||||
responseHeaders.set('Content-Type', contentType);
|
||||
const contentLength = backendRes.headers.get('content-length');
|
||||
if (contentLength) responseHeaders.set('Content-Length', contentLength);
|
||||
responseHeaders.set('Accept-Ranges', 'bytes');
|
||||
responseHeaders.set('Cache-Control', 'public, max-age=31536000, s-maxage=31536000, immutable');
|
||||
|
||||
return new NextResponse(null, {
|
||||
status: backendRes.status,
|
||||
headers: responseHeaders,
|
||||
});
|
||||
} catch (err: unknown) {
|
||||
console.error('[Media Proxy HEAD Error]', err);
|
||||
return new NextResponse(null, { status: 502 });
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import BlogPage from "../../components/BlogPage";
|
||||
import type { Metadata } from 'next';
|
||||
import { getPageMetadata } from "../../lib/seo";
|
||||
import { getMediaUrl } from "../../lib/media";
|
||||
|
||||
export async function generateMetadata(): Promise<Metadata> {
|
||||
return getPageMetadata('blog', {
|
||||
@@ -58,7 +59,7 @@ async function getBlogs() {
|
||||
? new Date(String(b.createdAt)).toLocaleDateString('fa-IR')
|
||||
: '',
|
||||
readingTime: b.readingTime || 3,
|
||||
image: String(b.imageUrl || b.coverImage || '/assets/images/blog-placeholder.png'),
|
||||
image: getMediaUrl(String(b.imageUrl || b.coverImage || '/assets/images/blog-placeholder.png')),
|
||||
imageAlt: b.imageAlt || b.title,
|
||||
author: authorName || 'نویسنده کنینا',
|
||||
content: String(b.content || ''),
|
||||
|
||||
@@ -17,6 +17,7 @@ import {
|
||||
ChevronUp
|
||||
} from "lucide-react";
|
||||
import SafeImage from "./SafeImage";
|
||||
import { getMediaUrl } from "../lib/media";
|
||||
|
||||
interface PodcastInlinePlayerProps {
|
||||
podcast: {
|
||||
@@ -177,7 +178,7 @@ export default function PodcastInlinePlayer({ podcast }: PodcastInlinePlayerProp
|
||||
return `${mins.toString().padStart(2, "0")}:${remainingSecs.toString().padStart(2, "0")}`;
|
||||
};
|
||||
|
||||
const displayCover = podcast.cover || podcast.fallbackCover || '/images/default-podcast.png';
|
||||
const displayCover = getMediaUrl(podcast.cover || podcast.fallbackCover || '/images/default-podcast.png');
|
||||
const progressPercent = duration > 0 ? (currentTime / duration) * 100 : 0;
|
||||
const volumePercent = isMuted ? 0 : volume * 100;
|
||||
|
||||
@@ -186,7 +187,7 @@ export default function PodcastInlinePlayer({ podcast }: PodcastInlinePlayerProp
|
||||
{/* Hidden Audio Tag */}
|
||||
<audio
|
||||
ref={audioRef}
|
||||
src={podcast.audioUrl}
|
||||
src={getMediaUrl(podcast.audioUrl)}
|
||||
preload="none"
|
||||
onPlay={() => setIsPlaying(true)}
|
||||
onPause={() => setIsPlaying(false)}
|
||||
|
||||
@@ -4,6 +4,7 @@ import Image from "next/image";
|
||||
import { Sparkles } from "lucide-react";
|
||||
import { cn } from "../lib/utils";
|
||||
import { useSettingsStore } from "../lib/store/settingsStore";
|
||||
import { getMediaUrl } from "../lib/media";
|
||||
|
||||
interface SafeImageProps extends Omit<React.ImgHTMLAttributes<HTMLImageElement>, 'src'> {
|
||||
src?: string;
|
||||
@@ -19,7 +20,7 @@ interface SafeImageProps extends Omit<React.ImgHTMLAttributes<HTMLImageElement>,
|
||||
}
|
||||
|
||||
export default function SafeImage({
|
||||
src,
|
||||
src: rawSrc,
|
||||
alt = "تصویر مکمل کنینا",
|
||||
className,
|
||||
imgClassName,
|
||||
@@ -34,6 +35,8 @@ export default function SafeImage({
|
||||
const [loading, setLoading] = React.useState(!priority);
|
||||
const logoUrl = useSettingsStore(state => state.getText('site_logo', ''));
|
||||
|
||||
const src = React.useMemo(() => getMediaUrl(rawSrc), [rawSrc]);
|
||||
|
||||
// Check if external domain is in allowed remote patterns or relative path
|
||||
const isExternal = typeof src === 'string' && (src.startsWith('http://') || src.startsWith('https://'));
|
||||
const isBlobOrData = typeof src === 'string' && (src.startsWith('blob:') || src.startsWith('data:'));
|
||||
|
||||
@@ -19,6 +19,7 @@ import {
|
||||
Sparkles,
|
||||
Loader2
|
||||
} from "lucide-react";
|
||||
import { getMediaUrl } from "../lib/media";
|
||||
|
||||
interface VideoModalPlayerProps {
|
||||
isOpen: boolean;
|
||||
@@ -317,8 +318,8 @@ export default function VideoModalPlayer({ isOpen, onClose, video }: VideoModalP
|
||||
>
|
||||
<video
|
||||
ref={videoRef}
|
||||
src={video.videoUrl}
|
||||
poster={video.thumbnail}
|
||||
src={getMediaUrl(video.videoUrl)}
|
||||
poster={getMediaUrl(video.thumbnail)}
|
||||
autoPlay
|
||||
playsInline
|
||||
onPlay={() => setIsPlaying(true)}
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
/**
|
||||
* Normalizes any media/upload URL to use the local frontend Next.js media proxy (/api/uploads/...)
|
||||
* instead of directly exposing or calling backend domains (api.canina.ir, etc.).
|
||||
*
|
||||
* Benefits:
|
||||
* 1. Leverages Next.js server caching and optimization.
|
||||
* 2. Hides internal backend URLs and avoids ugly direct backend domain calls.
|
||||
* 3. Supports HTTP Range requests for seamless video/audio seeking and streaming.
|
||||
*/
|
||||
export function getMediaUrl(url?: string | null): string {
|
||||
if (!url) return '';
|
||||
const trimmed = url.trim();
|
||||
if (!trimmed) return '';
|
||||
|
||||
// Data URLs or blob URLs stay as-is
|
||||
if (trimmed.startsWith('data:') || trimmed.startsWith('blob:')) {
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
// If already proxied via /api/uploads/ or /api/media/
|
||||
if (trimmed.startsWith('/api/uploads/') || trimmed.startsWith('/api/media/')) {
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
// If relative path starting with /uploads/
|
||||
if (trimmed.startsWith('/uploads/')) {
|
||||
return `/api/uploads/${trimmed.replace(/^\/uploads\//, '')}`;
|
||||
}
|
||||
|
||||
// If relative path starting with uploads/
|
||||
if (trimmed.startsWith('uploads/')) {
|
||||
return `/api/uploads/${trimmed.replace(/^uploads\//, '')}`;
|
||||
}
|
||||
|
||||
// If relative path starting with /media/ or media/
|
||||
if (trimmed.startsWith('/media/')) {
|
||||
return `/api/uploads/${trimmed.replace(/^\/media\//, '')}`;
|
||||
}
|
||||
if (trimmed.startsWith('media/')) {
|
||||
return `/api/uploads/${trimmed.replace(/^media\//, '')}`;
|
||||
}
|
||||
|
||||
// If full backend URL containing /uploads/ (e.g. http://localhost:4001/uploads/..., https://api.canina.ir/uploads/...)
|
||||
const uploadsMatch = trimmed.match(/^https?:\/\/[^/]+\/uploads\/(.+)$/i);
|
||||
if (uploadsMatch && uploadsMatch[1]) {
|
||||
return `/api/uploads/${uploadsMatch[1]}`;
|
||||
}
|
||||
|
||||
// External URLs (like unsplash, cdn, youtube, aparat) stay as-is
|
||||
return trimmed;
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import api from './api';
|
||||
import { PRODUCTS, Product, PetType } from "../data/products";
|
||||
import { Banner } from "../types";
|
||||
import { getMediaUrl } from "../media";
|
||||
|
||||
const CATEGORY_SLUG_TO_NAME: Record<string, string> = {
|
||||
'joints': 'مفاصل و استخوان',
|
||||
@@ -136,20 +137,12 @@ export class ProductService {
|
||||
feedingAdvice: data.dosageLogic || data.feedingAdvice || '',
|
||||
slug: data.slug,
|
||||
image: (() => {
|
||||
const apiBase = (process.env.NEXT_PUBLIC_API_URL || '').replace(/\/api$/, '');
|
||||
if (!data.imageUrl) return local?.image || '/assets/images/hero-section-image.png';
|
||||
if (data.imageUrl.startsWith('http://') || data.imageUrl.startsWith('https://')) return data.imageUrl;
|
||||
if (data.imageUrl.startsWith('/uploads/')) return `${apiBase}${data.imageUrl}`;
|
||||
if (data.imageUrl.startsWith('/products/')) return local?.image || '/assets/images/hero-section-image.png';
|
||||
return local?.image || data.imageUrl || '/assets/images/hero-section-image.png';
|
||||
return getMediaUrl(data.imageUrl) || local?.image || '/assets/images/hero-section-image.png';
|
||||
})(),
|
||||
images: Array.isArray(data.images) && data.images.length > 0
|
||||
? data.images.map((img: string) => {
|
||||
const apiBase = (process.env.NEXT_PUBLIC_API_URL || '').replace(/\/api$/, '');
|
||||
if (img.startsWith('http://') || img.startsWith('https://')) return img;
|
||||
if (img.startsWith('/uploads/')) return `${apiBase}${img}`;
|
||||
return img;
|
||||
})
|
||||
? data.images.map((img: string) => getMediaUrl(img)).filter(Boolean)
|
||||
: (local?.images || []),
|
||||
|
||||
main_ingredients: data.ingredientList?.map(i => i.ingredient) || data.ingredients?.split(/[،,-]/).map(s => s.trim()).filter(Boolean) || [],
|
||||
@@ -160,56 +153,20 @@ export class ProductService {
|
||||
specialist: safeParse<Product['specialist']>(data.specialist, defaultSpecialist),
|
||||
|
||||
calculateDosage: local?.calculateDosage,
|
||||
podcastUrl: (() => {
|
||||
const apiBase = (process.env.NEXT_PUBLIC_API_URL || '').replace(/\/api$/, '');
|
||||
if (!data.podcastUrl) return undefined;
|
||||
if (data.podcastUrl.startsWith('http://') || data.podcastUrl.startsWith('https://')) return data.podcastUrl;
|
||||
if (data.podcastUrl.startsWith('/uploads/')) return `${apiBase}${data.podcastUrl}`;
|
||||
return data.podcastUrl;
|
||||
})(),
|
||||
podcastUrl: data.podcastUrl ? getMediaUrl(data.podcastUrl) : undefined,
|
||||
podcastTitle: data.podcastTitle || undefined,
|
||||
podcastDescription: data.podcastDescription || undefined,
|
||||
podcastCover: (() => {
|
||||
const apiBase = (process.env.NEXT_PUBLIC_API_URL || '').replace(/\/api$/, '');
|
||||
if (!data.podcastCover) return undefined;
|
||||
if (data.podcastCover.startsWith('http://') || data.podcastCover.startsWith('https://')) return data.podcastCover;
|
||||
if (data.podcastCover.startsWith('/uploads/')) return `${apiBase}${data.podcastCover}`;
|
||||
return data.podcastCover;
|
||||
})(),
|
||||
podcastCover: data.podcastCover ? getMediaUrl(data.podcastCover) : undefined,
|
||||
|
||||
videoUrl: (() => {
|
||||
const apiBase = (process.env.NEXT_PUBLIC_API_URL || '').replace(/\/api$/, '');
|
||||
if (!data.videoUrl) return undefined;
|
||||
if (data.videoUrl.startsWith('http://') || data.videoUrl.startsWith('https://')) return data.videoUrl;
|
||||
if (data.videoUrl.startsWith('/uploads/')) return `${apiBase}${data.videoUrl}`;
|
||||
return data.videoUrl;
|
||||
})(),
|
||||
videoUrl: data.videoUrl ? getMediaUrl(data.videoUrl) : undefined,
|
||||
videoTitle: data.videoTitle || undefined,
|
||||
videoDescription: data.videoDescription || undefined,
|
||||
videoCover: (() => {
|
||||
const apiBase = (process.env.NEXT_PUBLIC_API_URL || '').replace(/\/api$/, '');
|
||||
if (!data.videoCover) return undefined;
|
||||
if (data.videoCover.startsWith('http://') || data.videoCover.startsWith('https://')) return data.videoCover;
|
||||
if (data.videoCover.startsWith('/uploads/')) return `${apiBase}${data.videoCover}`;
|
||||
return data.videoCover;
|
||||
})(),
|
||||
videoCover: data.videoCover ? getMediaUrl(data.videoCover) : undefined,
|
||||
|
||||
pdfUrl: (() => {
|
||||
const apiBase = (process.env.NEXT_PUBLIC_API_URL || '').replace(/\/api$/, '');
|
||||
if (!data.pdfUrl) return undefined;
|
||||
if (data.pdfUrl.startsWith('http://') || data.pdfUrl.startsWith('https://')) return data.pdfUrl;
|
||||
if (data.pdfUrl.startsWith('/uploads/')) return `${apiBase}${data.pdfUrl}`;
|
||||
return data.pdfUrl;
|
||||
})(),
|
||||
pdfUrl: data.pdfUrl ? getMediaUrl(data.pdfUrl) : undefined,
|
||||
pdfTitle: data.pdfTitle || undefined,
|
||||
pdfDescription: data.pdfDescription || undefined,
|
||||
pdfCover: (() => {
|
||||
const apiBase = (process.env.NEXT_PUBLIC_API_URL || '').replace(/\/api$/, '');
|
||||
if (!data.pdfCover) return undefined;
|
||||
if (data.pdfCover.startsWith('http://') || data.pdfCover.startsWith('https://')) return data.pdfCover;
|
||||
if (data.pdfCover.startsWith('/uploads/')) return `${apiBase}${data.pdfCover}`;
|
||||
return data.pdfCover;
|
||||
})(),
|
||||
pdfCover: data.pdfCover ? getMediaUrl(data.pdfCover) : undefined,
|
||||
barcode: (inputData.barcode as string) || undefined,
|
||||
metaTitle: (inputData.metaTitle as string) || undefined,
|
||||
metaDescription: (inputData.metaDescription as string) || undefined,
|
||||
@@ -218,14 +175,7 @@ export class ProductService {
|
||||
stockStatus: (inputData.stockStatus as 'IN_STOCK' | 'OUT_OF_STOCK' | 'PRE_ORDER' | 'DISCONTINUED') || 'IN_STOCK',
|
||||
noIndex: Boolean(inputData.noIndex),
|
||||
noFollow: Boolean(inputData.noFollow),
|
||||
ogImage: (() => {
|
||||
const apiBase = (process.env.NEXT_PUBLIC_API_URL || '').replace(/\/api$/, '');
|
||||
const og = inputData.ogImage as string;
|
||||
if (!og) return undefined;
|
||||
if (og.startsWith('http://') || og.startsWith('https://')) return og;
|
||||
if (og.startsWith('/uploads/')) return `${apiBase}${og}`;
|
||||
return og;
|
||||
})(),
|
||||
ogImage: inputData.ogImage ? getMediaUrl(inputData.ogImage as string) : undefined,
|
||||
featuredImageAlt: (inputData.featuredImageAlt as string) || undefined,
|
||||
updatedAt: (inputData.updatedAt as string) || (inputData.createdAt as string) || undefined,
|
||||
reviews: Array.isArray(inputData.reviews) ? inputData.reviews as Product['reviews'] : undefined,
|
||||
@@ -372,7 +322,11 @@ export class ProductService {
|
||||
public async getBanners(): Promise<Banner[]> {
|
||||
try {
|
||||
const response = await api.get('/banners');
|
||||
return response.data || [];
|
||||
const data = response.data || [];
|
||||
return data.map((b: Banner) => ({
|
||||
...b,
|
||||
imageUrl: getMediaUrl(b.imageUrl),
|
||||
}));
|
||||
} catch (error) {
|
||||
console.error("[ProductService] Failed to fetch banners:", error);
|
||||
return [];
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import api from './api';
|
||||
import { getMediaUrl } from '../media';
|
||||
|
||||
export interface Video {
|
||||
id: string;
|
||||
@@ -12,16 +13,31 @@ export interface Video {
|
||||
isFeatured?: boolean;
|
||||
}
|
||||
|
||||
function normalizeVideo(v: any): Video {
|
||||
return {
|
||||
id: String(v.id || ''),
|
||||
title: String(v.title || ''),
|
||||
doctor: String(v.doctor || 'کادر علمی کنینا'),
|
||||
duration: String(v.duration || '۳:۰۰'),
|
||||
thumbnail: getMediaUrl(v.thumbnail || v.coverUrl || '/assets/images/hero-section-image.png'),
|
||||
videoUrl: getMediaUrl(v.videoUrl || ''),
|
||||
description: String(v.description || ''),
|
||||
viewsCount: Number(v.viewsCount) || 0,
|
||||
isFeatured: Boolean(v.isFeatured),
|
||||
};
|
||||
}
|
||||
|
||||
export const videoService = {
|
||||
getVideos: async (params?: { featured?: boolean; limit?: number; search?: string }) => {
|
||||
getVideos: async (params?: { featured?: boolean; limit?: number; search?: string }): Promise<Video[]> => {
|
||||
try {
|
||||
const res = await api.get('/videos', { params });
|
||||
const raw = res.data;
|
||||
if (Array.isArray(raw?.videos)) return raw.videos;
|
||||
if (Array.isArray(raw?.data?.videos)) return raw.data.videos;
|
||||
if (Array.isArray(raw?.data)) return raw.data;
|
||||
if (Array.isArray(raw)) return raw;
|
||||
return [];
|
||||
let items: any[] = [];
|
||||
if (Array.isArray(raw?.videos)) items = raw.videos;
|
||||
else if (Array.isArray(raw?.data?.videos)) items = raw.data.videos;
|
||||
else if (Array.isArray(raw?.data)) items = raw.data;
|
||||
else if (Array.isArray(raw)) items = raw;
|
||||
return items.map(normalizeVideo);
|
||||
} catch (error) {
|
||||
console.error('Failed to fetch videos from API:', error);
|
||||
return [];
|
||||
|
||||
Reference in new issue
Block a user