ProductCarousel.tsx 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. import { FC } from "react";
  2. import { cachedGraphQLRequest } from "@/utils/hooks/useCache";
  3. import { ThreeItemGrid } from "./ThreeItemGrid";
  4. import Theme from "./ProductCarouselTheme";
  5. import { GET_PRODUCTS } from "@/graphql";
  6. interface ProductCarouselProps {
  7. options: {
  8. title?: string;
  9. filters: Record<string, any>;
  10. };
  11. itemCount?: number;
  12. sortOrder?: number;
  13. }
  14. const ProductCarousel: FC<ProductCarouselProps> = async ({
  15. options,
  16. itemCount = 4,
  17. sortOrder,
  18. }) => {
  19. const { filters, title } = options;
  20. const { sort, limit, ...rest } = filters || {};
  21. const filterObject: Record<string, string> = {};
  22. Object.entries(rest).forEach(([key, value]) => {
  23. if (value !== undefined && value !== null) {
  24. filterObject[key] = String(value);
  25. }
  26. });
  27. const filterInput =
  28. Object.keys(filterObject).length > 0
  29. ? JSON.stringify(filterObject)
  30. : undefined;
  31. let sortKey = "CREATED_AT";
  32. let reverse = true;
  33. if (sort === "created_at-desc") {
  34. sortKey = "CREATED_AT";
  35. reverse = true;
  36. } else if (sort === "price-desc") {
  37. sortKey = "PRICE";
  38. reverse = true;
  39. }
  40. const {data} = await cachedGraphQLRequest<any>(
  41. "home",
  42. GET_PRODUCTS,
  43. {
  44. sortKey,
  45. filter: filterInput,
  46. first: limit ? parseInt(limit, 10) : itemCount,
  47. reverse,
  48. }
  49. );
  50. const products =
  51. data?.products?.edges?.slice(0, 8).map((edge: any) => edge.node) || [];
  52. if (!products.length) {
  53. return null;
  54. }
  55. if (sortOrder === 2) {
  56. return (
  57. <ThreeItemGrid
  58. title={title || "Products"}
  59. description="Discover the latest trends! Fresh products just added—shop new styles, tech, and essentials before they're gone."
  60. products={products.slice(0, 3)}
  61. />
  62. );
  63. }
  64. return (
  65. <Theme
  66. title={title || "Products"}
  67. description="Discover the latest trends! Fresh products just added—shop new styles, tech, and essentials before they're gone."
  68. products={products}
  69. />
  70. );
  71. };
  72. export default ProductCarousel;