Rest95

CategoriesQuery.js

Dec 9th, 2021
873
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import { getQueryStringProps } from "qs-props";
  2.  
  3. export async function getStaticPathsCategories(locales) {
  4.   let paths = [];
  5.  
  6.   for (const locale of locales) {
  7.     const res = await fetch(
  8.       `${process.env.NEXT_PUBLIC_API_URL}categories/frontendfind?_locale=${locale}`
  9.     );
  10.     const data = await res.json();
  11.  
  12.     paths = [
  13.       ...paths,
  14.       ...data.map((category) => {
  15.         return {
  16.           params: {
  17.             query: [
  18.               category.slug.toString().replace(`-${locale.toLowerCase()}`, ""),
  19.               "query.{}",
  20.             ],
  21.           },
  22.           locale: locale,
  23.         };
  24.       }),
  25.     ];
  26.   }
  27.  
  28.   return {
  29.     paths: paths,
  30.     fallback: "blocking",
  31.   };
  32. }
  33.  
  34. // export const getQuery = (params) => {
  35. //   const paths = params?.query;
  36. //   if (Array.isArray(paths)) {
  37. //     const q = paths.find((p) => p.startsWith("query."));
  38. //     return !q ? q : JSON.parse(q.replace(/^query\./, ""));
  39. //   }
  40. //   return undefined;
  41. // };
  42.  
  43. export async function getStaticPropsCategories(context) {
  44.   // const queryParams = {};
  45.   const queryParams = getQueryStringProps(context, "query");
  46.   console.log(queryParams);
  47.   const { query } = context.params;
  48.   if (query.length === 0) {
  49.     return {
  50.       notFound: true,
  51.     };
  52.   }
  53.   const slug = query[0];
  54.   const { locale, defaultLocale } = context;
  55.  
  56.   const res = await fetch(
  57.     `${process.env.NEXT_PUBLIC_API_URL}categories/frontendfind?slug_contains=${slug}&_locale=${locale}`
  58.   );
  59.  
  60.   if (res.status === 404) {
  61.     return {
  62.       notFound: true,
  63.     };
  64.   }
  65.   const data = await res.json();
  66.   if (!data && data.length === 0) {
  67.     return {
  68.       notFound: true,
  69.     };
  70.   }
  71.  
  72.   if (data.length > 0) {
  73.     let translation =
  74.       data.length >= 1 &&
  75.       data[0].localizations.find((l) => l.locale === locale);
  76.  
  77.     if (data[0].locale !== locale && translation) {
  78.       const resCategory = await fetch(
  79.         `${process.env.NEXT_PUBLIC_API_URL}categories/findbyid/${translation.id}`
  80.       );
  81.       const dataCategory = await resCategory.json();
  82.       return {
  83.         redirect: {
  84.           destination: `/categories/${dataCategory.slug.replace(
  85.             `-${locale.toLowerCase()}`,
  86.             ""
  87.           )}`,
  88.           permanent: false,
  89.         },
  90.       };
  91.     }
  92.   }
  93.  
  94.   const resAttributes = await fetch(
  95.     `${process.env.NEXT_PUBLIC_API_URL}attributes/store/find?_locale=${locale}`
  96.   );
  97.   const dataAttributes = await resAttributes.json();
  98.  
  99.   let searchQuery = ``;
  100.   let orderQuery = `&_sort=order_value:DESC`;
  101.   let pagination = `&_start=0&_limit=${process.env.NEXT_PUBLIC_PER_PAGE}`;
  102.  
  103.   let haveAttributesToSearch = false;
  104.   if (queryParams) {
  105.     if (Object.keys(queryParams).length !== 0) {
  106.       for (const [key, value] of Object.entries(queryParams)) {
  107.         if (key.includes("attr_")) {
  108.           haveAttributesToSearch = true;
  109.         }
  110.       }
  111.       if (haveAttributesToSearch) {
  112.         searchQuery += `&sellable_items.stock_gte=1`;
  113.       }
  114.       for (const [key, value] of Object.entries(queryParams)) {
  115.         if (key.includes("attr_")) {
  116.           let attr_key = key.replace("attr_", "");
  117.           if (value.length > 0) {
  118.             value.forEach((v) => {
  119.               searchQuery += `&sellable_items.search_string_contains=${attr_key}-${v}`;
  120.             });
  121.           }
  122.         } else if (key === "order_by") {
  123.           if (value.split(":")[0] === "price") {
  124.             orderQuery = `&_sort=sellable_items.price:${value.split(":")[1]}`;
  125.           } else if (value.split(":")[0] === "created_at") {
  126.             orderQuery = `&_sort=created_at:${value.split(":")[1]}`;
  127.           } else if (value.split(":")[0] === "our_choices") {
  128.             orderQuery = `&_sort=order_value:DESC`;
  129.           }
  130.         } else if (key === "page") {
  131.           pagination = `&_start=${
  132.             (value - 1) * process.env.NEXT_PUBLIC_PER_PAGE
  133.           }&_limit=${process.env.NEXT_PUBLIC_PER_PAGE}`;
  134.         } else {
  135.           searchQuery += `&${key}=${value}`;
  136.         }
  137.       }
  138.     }
  139.   }
  140.   searchQuery += `${searchQuery}${orderQuery}`;
  141.   const resProducts = await fetch(
  142.     `${process.env.NEXT_PUBLIC_API_URL}products/store/find?categories_in=${data[0].id}&published_at_null=false${searchQuery}${pagination}&_locale=${locale}`
  143.   );
  144.   const dataProducts = await resProducts.json();
  145.  
  146.   return {
  147.     props: {
  148.       category: data[0],
  149.       attributes: dataAttributes,
  150.       products: dataProducts,
  151.     },
  152.     revalidate: 86400,
  153.   };
  154. }
  155.  
RAW Paste Data