summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorit-fixcomart <it@fixcomart.co.id>2024-11-13 10:08:16 +0700
committerit-fixcomart <it@fixcomart.co.id>2024-11-13 10:08:16 +0700
commit0d3c0cf6a00ef81bfdb944490e48f16af41fc029 (patch)
treead5dd0c580c33d4856455a1272a31ce8349ddda9
parent0ecb7ba546cd1fdd3811f76aa09b20642ab4952c (diff)
<iman> add radis
-rw-r--r--src-migrate/modules/page-content/index.tsx33
-rw-r--r--src/components/ui/HeroBannerSecondary.jsx69
-rw-r--r--src/core/components/elements/Navbar/TopBanner.jsx53
-rw-r--r--src/lib/home/components/CategoryDynamicMobile.jsx23
-rw-r--r--src/pages/api/hero-banner.js4
-rw-r--r--src/pages/api/page-content.js44
-rw-r--r--src/pages/api/shop/brands.js3
7 files changed, 136 insertions, 93 deletions
diff --git a/src-migrate/modules/page-content/index.tsx b/src-migrate/modules/page-content/index.tsx
index 3423ca8b..54ee0a04 100644
--- a/src-migrate/modules/page-content/index.tsx
+++ b/src-migrate/modules/page-content/index.tsx
@@ -10,28 +10,21 @@ type Props = {
const PageContent = ({ path }: Props) => {
const [localData, setData] = useState<PageContentProps>();
const [shouldFetch, setShouldFetch] = useState(false);
+ const [isLoading, setIsLoading] = useState(false);
useEffect(() => {
- const localData = localStorage.getItem(`page-content:${path}`);
- if (localData) {
- setData(JSON.parse(localData));
- }else{
- setShouldFetch(true);
- }
- },[])
-
- const { data, isLoading } = useQuery<PageContentProps>(
- `page-content:${path}`,
- async () => await getPageContent({ path }), {
- enabled: shouldFetch,
- onSuccess: (data) => {
- if (data) {
- localStorage.setItem(`page-content:${path}`, JSON.stringify(data));
- setData(data);
- }
- },
- }
- );
+ const fetchData = async () => {
+ setIsLoading(true);
+ const res = await fetch(`/api/page-content?path=${path}`);
+ const { data } = await res.json();
+ if (data) {
+ setData(data);
+ }
+ setIsLoading(false);
+ };
+
+ fetchData();
+ }, []);
const parsedContent = useMemo<string>(() => {
if (!localData) return '';
diff --git a/src/components/ui/HeroBannerSecondary.jsx b/src/components/ui/HeroBannerSecondary.jsx
index a7b32a4a..6074c9a6 100644
--- a/src/components/ui/HeroBannerSecondary.jsx
+++ b/src/components/ui/HeroBannerSecondary.jsx
@@ -1,39 +1,58 @@
-import Link from '@/core/components/elements/Link/Link'
-import { getRandomInt } from '@/utils/getRandomInt'
-import Image from 'next/image'
-import { useMemo } from 'react'
-import { useQuery } from 'react-query'
-import { HeroBannerSkeleton } from '../skeleton/BannerSkeleton'
-import { bannerApi } from '@/api/bannerApi'
+import Link from '@/core/components/elements/Link/Link';
+import { getRandomInt } from '@/utils/getRandomInt';
+import Image from 'next/image';
+import { useMemo, useEffect, useState } from 'react';
+import { useQuery } from 'react-query';
+import { HeroBannerSkeleton } from '../skeleton/BannerSkeleton';
+import { bannerApi } from '@/api/bannerApi';
const HeroBannerSecondary = () => {
- const heroBannerSecondary = useQuery('heroBannerSecondary', bannerApi({ type: 'index-a-2' }))
+ const [heroBannerSecondary, setHeroBannerSecondary] = useState([]);
+ const [isLoading, setIsLoading] = useState(false);
+ // const heroBannerSecondary = useQuery(
+ // 'heroBannerSecondary',
+ // bannerApi({ type: 'index-a-2' })
+ // );
- const randomIndex = useMemo(() => {
- if (!heroBannerSecondary.data) return null
- const length = heroBannerSecondary.data?.length
- return getRandomInt(length)
- }, [heroBannerSecondary.data])
+ useEffect(() => {
+ const fetchData = async () => {
+ setIsLoading(true);
+ const res = await fetch(`/api/hero-banner?type=index-a-2`);
+ const { data } = await res.json();
+ if (data) {
+ setHeroBannerSecondary(data);
+ }
+ setIsLoading(false);
+ };
+
+ fetchData();
+ }, []);
- if (heroBannerSecondary.isLoading) return <HeroBannerSkeleton />
+ const randomIndex = useMemo(() => {
+ if (!heroBannerSecondary) return null;
+ const length = heroBannerSecondary?.length;
+ return getRandomInt(length);
+ }, [heroBannerSecondary]);
+ if (isLoading) return <HeroBannerSkeleton />;
return (
- heroBannerSecondary.data && randomIndex !== null && (
- <Link href={heroBannerSecondary.data[randomIndex].url} className="h-full">
+ heroBannerSecondary &&
+ randomIndex !== null && (
+ <Link href={heroBannerSecondary[randomIndex]?.url} className='h-full'>
<Image
- src={heroBannerSecondary.data[randomIndex].image}
+ src={heroBannerSecondary[randomIndex]?.image}
width={512}
height={1024}
- alt={heroBannerSecondary.data[randomIndex].name}
- className="object-cover object-center h-full"
- loading="lazy"
- placeholder="blur"
- blurDataURL="/images/indoteknik-placeholder.png"
- sizes="(max-width: 768px) 100vw, 50vw"
+ alt={heroBannerSecondary[randomIndex]?.name}
+ className='object-cover object-center h-full'
+ loading='lazy'
+ placeholder='blur'
+ blurDataURL='/images/indoteknik-placeholder.png'
+ sizes='(max-width: 768px) 100vw, 50vw'
/>
</Link>
)
);
-}
+};
-export default HeroBannerSecondary
+export default HeroBannerSecondary;
diff --git a/src/core/components/elements/Navbar/TopBanner.jsx b/src/core/components/elements/Navbar/TopBanner.jsx
index f438ae67..709495ce 100644
--- a/src/core/components/elements/Navbar/TopBanner.jsx
+++ b/src/core/components/elements/Navbar/TopBanner.jsx
@@ -1,22 +1,37 @@
import Image from 'next/image';
-import { useQuery } from 'react-query';import useDevice from '@/core/hooks/useDevice'
+import { useQuery } from 'react-query';
+import useDevice from '@/core/hooks/useDevice';
import odooApi from '@/core/api/odooApi';
import SmoothRender from '~/components/ui/smooth-render';
import Link from '../Link/Link';
import { background } from '@chakra-ui/react';
-import { useEffect } from 'react';
+import { useEffect, useState } from 'react';
const TopBanner = ({ onLoad = () => {} }) => {
- const { isDesktop, isMobile } = useDevice()
- const topBanner = useQuery({
- queryKey: 'topBanner',
- queryFn: async () => await odooApi('GET', '/api/v1/banner?type=top-banner'),
- refetchOnWindowFocus: false,
- });
+ const [topBanner, setTopBanner] = useState([]);
+ const { isDesktop, isMobile } = useDevice();
+
+ useEffect(() => {
+ const fetchData = async () => {
+ const res = await fetch(`/api/hero-banner?type=top-banner`);
+ const { data } = await res.json();
+ if (data) {
+ setTopBanner(data);
+ }
+ };
+
+ fetchData();
+ }, []);
+
+ // const topBanner = useQuery({
+ // queryKey: 'topBanner',
+ // queryFn: async () => await odooApi('GET', '/api/v1/banner?type=top-banner'),
+ // refetchOnWindowFocus: false,
+ // });
// const backgroundColor = topBanner.data?.[0]?.backgroundColor || 'transparent';
- const hasData = topBanner.data?.length > 0;
- const data = topBanner.data?.[0] || null;
+ const hasData = topBanner?.length > 0;
+ const data = topBanner?.[0] || null;
useEffect(() => {
if (hasData) {
@@ -31,17 +46,15 @@ const TopBanner = ({ onLoad = () => {} }) => {
duration='700ms'
delay='300ms'
className='h-auto'
- >
+ >
<Link
- href={data?.url}
- className="block bg-cover bg-center h-3 md:h-6 lg:h-[36px]"
- style={{
- backgroundImage: `url('${data?.image}')`,
- }}
- >
- </Link>
-
- </SmoothRender>
+ href={data?.url}
+ className='block bg-cover bg-center h-3 md:h-6 lg:h-[36px]'
+ style={{
+ backgroundImage: `url('${data?.image}')`,
+ }}
+ ></Link>
+ </SmoothRender>
);
};
diff --git a/src/lib/home/components/CategoryDynamicMobile.jsx b/src/lib/home/components/CategoryDynamicMobile.jsx
index 6ede1147..67ae6f5f 100644
--- a/src/lib/home/components/CategoryDynamicMobile.jsx
+++ b/src/lib/home/components/CategoryDynamicMobile.jsx
@@ -9,29 +9,6 @@ import {
fetchCategoryManagementVersion,
} from '../api/categoryManagementApi';
-const saveToLocalStorage = (key, data, version) => {
- const now = new Date();
- const item = {
- value: data,
- version: version,
- lastFetchedTime: now.getTime(),
- };
- localStorage.setItem(key, JSON.stringify(item));
-};
-
-const getFromLocalStorage = (key) => {
- const itemStr = localStorage.getItem(key);
- if (!itemStr) return null;
-
- const item = JSON.parse(itemStr);
- return item;
-};
-
-const getElapsedTime = (lastFetchedTime) => {
- const now = new Date();
- return now.getTime() - lastFetchedTime;
-};
-
const CategoryDynamicMobile = () => {
const [selectedCategory, setSelectedCategory] = useState({});
const [categoryManagement, setCategoryManagement] = useState([]);
diff --git a/src/pages/api/hero-banner.js b/src/pages/api/hero-banner.js
index b57f86e0..7a348cfa 100644
--- a/src/pages/api/hero-banner.js
+++ b/src/pages/api/hero-banner.js
@@ -35,8 +35,8 @@ export default async function handler(req, res) {
'EX',
259200
);
-
- return res.status(200).json({ data: dataBannerSections });
+ cachedData = await client.get(cacheKey);
+ return res.status(200).json({ data: cachedData });
}
} catch (error) {
console.error('Error interacting with Redis or fetching data:', error);
diff --git a/src/pages/api/page-content.js b/src/pages/api/page-content.js
new file mode 100644
index 00000000..3cb8a237
--- /dev/null
+++ b/src/pages/api/page-content.js
@@ -0,0 +1,44 @@
+import { createClient } from 'redis';
+import { getPageContent } from '~/services/pageContent';
+// import { fetchCategoryManagementSolr } from '../../lib/home/api/categoryManagementApi';
+const client = createClient();
+client.on('error', (err) => console.error('Redis Client Error', err));
+
+const connectRedis = async () => {
+ if (!client.isOpen) {
+ await client.connect();
+ }
+};
+
+export default async function handler(req, res) {
+ const { path } = req.query;
+ try {
+ await connectRedis();
+ // await client.del('onbording-popup');
+
+ let cachedData;
+ if (req.method === 'GET') {
+ cachedData = await client.get(`page-content:${path}`);
+
+ if (!cachedData) {
+ const items = await getPageContent({ path });
+ console.log('items', items);
+ await client.set(
+ `page-content:${path}`,
+ JSON.stringify(items),
+ 'EX',
+ 604800 // Expiry 1 minggu
+ );
+ cachedData = await client.get(`page-content:${path}`);
+ }
+ const data = cachedData ? JSON.parse(cachedData) : null;
+ res.status(200).json({ data });
+ } else {
+ res.setHeader('Allow', ['GET']);
+ res.status(405).end(`Method ${req.method} Not Allowed`);
+ }
+ } catch (error) {
+ console.error('Error interacting with Redis:', error);
+ res.status(500).json({ error: 'Error interacting with Redis' });
+ }
+}
diff --git a/src/pages/api/shop/brands.js b/src/pages/api/shop/brands.js
index 380b3369..219f2cb0 100644
--- a/src/pages/api/shop/brands.js
+++ b/src/pages/api/shop/brands.js
@@ -42,16 +42,13 @@ export default async function handler(req, res) {
let cachedData = await client.get(cacheKey);
if (cachedData) {
- console.log('Retrieving data from Redis cache');
return res.status(200).json(JSON.parse(cachedData));
}
- // Fetch data from Solr
const url = `${SOLR_HOST}/solr/brands/select?q=${params}&q.op=OR&indent=true&rows=${rows}&${sort}`;
const brands = await axios(url);
const dataBrands = responseMap(brands.data.response.docs);
- // Store fetched data in Redis with 3-day expiration
await client.set(cacheKey, JSON.stringify(dataBrands), 'EX', 259200);
res.status(200).json(dataBrands);