summaryrefslogtreecommitdiff
path: root/src/pages/api/shop/search.js
diff options
context:
space:
mode:
Diffstat (limited to 'src/pages/api/shop/search.js')
-rw-r--r--src/pages/api/shop/search.js188
1 files changed, 159 insertions, 29 deletions
diff --git a/src/pages/api/shop/search.js b/src/pages/api/shop/search.js
index 1f636f28..8954446a 100644
--- a/src/pages/api/shop/search.js
+++ b/src/pages/api/shop/search.js
@@ -1,6 +1,11 @@
import { productMappingSolr } from '@/utils/solrMapping';
import axios from 'axios';
import camelcaseObjectDeep from 'camelcase-object-deep';
+import {
+ chunkArray,
+ buildProductIdOrClause,
+ mergeSolrResults,
+} from '@/lib/utils/batchSolrQueries';
const escapeSolrQuery = (query) => {
if (query == '*') return query;
@@ -14,7 +19,26 @@ const escapeSolrQuery = (query) => {
.join(' ');
};
+/**
+ * Get parameter value from either GET (req.query) or POST (req.body)
+ * POST takes precedence if available
+ */
+const getParam = (req, key, defaultValue = undefined) => {
+ // POST takes precedence
+ if (req.body && req.body[key] !== undefined) {
+ return req.body[key];
+ }
+ // Fallback to GET
+ if (req.query && req.query[key] !== undefined) {
+ return req.query[key];
+ }
+ return defaultValue;
+};
+
export default async function handler(req, res) {
+ // Support both GET and POST requests
+ const params = req.method === 'POST' ? req.body : req.query;
+
const {
q = '*',
page = 1,
@@ -28,9 +52,15 @@ export default async function handler(req, res) {
limit = 30,
source = '',
group = 'true',
- } = req.query;
+ } = params;
- let { stock = '' } = req.query;
+ let { stock = '' } = params;
+
+ // Convert string parameters to appropriate types (for POST requests)
+ const pageNum = parseInt(page, 10) || 1;
+ const limitNum = parseInt(limit, 10) || 30;
+ const priceFromNum = parseFloat(priceFrom) || 0;
+ const priceToNum = parseFloat(priceTo) || 0;
// ============================================================
// [PERBAIKAN] 1. LOGIC KHUSUS COMPARE (PAKAI URLSearchParams)
@@ -56,7 +86,7 @@ export default async function handler(req, res) {
const params = new URLSearchParams();
params.append('q', qCompare);
- params.append('rows', limit);
+ params.append('rows', limitNum);
params.append('wt', 'json');
params.append('indent', 'true');
@@ -218,7 +248,7 @@ export default async function handler(req, res) {
// ============================================================
if (source === 'sitemap') {
try {
- const offset = (page - 1) * limit;
+ const offset = (pageNum - 1) * limitNum;
const parameter = [
'q=*:*',
`rows=${limit}`,
@@ -311,7 +341,7 @@ export default async function handler(req, res) {
keywords = formattedQuery;
}
- let offset = (page - 1) * limit;
+ let offset = (pageNum - 1) * limitNum;
let parameter = [
'facet.field={!ex=brand}manufacture_name_s',
@@ -334,9 +364,9 @@ export default async function handler(req, res) {
parameter.push(`fq=${encodeURIComponent(f)}`);
});
- if (priceFrom > 0 || priceTo > 0) {
+ if (priceFromNum > 0 || priceToNum > 0) {
parameter.push(
- `fq=price_tier1_v2_f:[${priceFrom || '*'} TO ${priceTo || '*'}]`,
+ `fq=price_tier1_v2_f:[${priceFromNum || '*'} TO ${priceToNum || '*'}]`,
);
}
@@ -371,39 +401,139 @@ export default async function handler(req, res) {
fq.map((val) => `fq=${encodeURIComponent(val)}`),
);
- // Searchkey
- if (req.query.from === 'searchkey') {
- const ids = req.query.ids ? req.query.ids.split(',').filter(Boolean) : [];
+ // Searchkey with batching for large ID arrays
+ if (params.from === 'searchkey') {
+ try {
+ // Extract IDs from either query params (GET) or body (POST)
+ let ids = [];
+
+ if (req.method === 'POST' && req.body && req.body.ids) {
+ // POST request: IDs in body
+ ids = Array.isArray(req.body.ids)
+ ? req.body.ids
+ : req.body.ids.split(',').filter(Boolean);
+ } else if (req.query.ids) {
+ // GET request: IDs in query params
+ ids = req.query.ids.split(',').filter(Boolean);
+ }
- const q = ids.map((id) => `product_id_i:${id}`).join(' OR ');
+ if (ids.length === 0) {
+ return res.status(400).json({ error: 'No product IDs provided' });
+ }
- const strictQuery = [
- `q=${encodeURIComponent(q)}`,
- `fq=-publish_b:false AND price_tier1_v2_f:[1 TO *] AND product_rating_f:[8 TO *]`,
- // `qf=variants_code_t variants_name_t`,
- `rows=${limit}`,
- `start=${offset}`,
- `sort=${paramOrderBy}`,
- ];
+ console.log(`[SEARCHKEY] Processing ${ids.length} product IDs`);
- const solrUrl =
- process.env.SOLR_HOST + '/solr/product/select?' + strictQuery.join('&');
+ // If less than 100 IDs, use single query
+ if (ids.length <= 100) {
+ const q = buildProductIdOrClause(ids);
- console.log('[SEARCHKEY FINAL QUERY]', solrUrl);
+ const strictQuery = [
+ `q=${encodeURIComponent(q)}`,
+ `fq=-publish_b:false AND price_tier1_v2_f:[1 TO *] AND product_rating_f:[8 TO *]`,
+ `rows=${limitNum}`,
+ `start=${offset}`,
+ `sort=${paramOrderBy}`,
+ ];
- const result = await axios(solrUrl);
+ const solrUrl =
+ process.env.SOLR_HOST +
+ '/solr/product/select?' +
+ strictQuery.join('&');
- try {
- result.data.response.products = productMappingSolr(
- result.data.response.docs,
+ console.log('[SEARCHKEY SINGLE QUERY]', solrUrl);
+
+ const result = await axios(solrUrl);
+ result.data.response.products = productMappingSolr(
+ result.data.response.docs,
+ auth?.pricelist || false,
+ );
+
+ delete result.data.response.docs;
+ result.data = camelcaseObjectDeep(result.data);
+
+ return res.status(200).json(result.data);
+ }
+
+ // Batch large ID arrays into chunks of 100
+ const idChunks = chunkArray(ids, 100);
+ console.log(
+ `[SEARCHKEY BATCH] Splitting ${ids.length} IDs into ${idChunks.length} chunks`,
+ );
+
+ // Execute all chunk queries in parallel
+ const batchQueries = idChunks.map((chunk) => {
+ const q = buildProductIdOrClause(chunk);
+ const queryParams = [
+ `q=${encodeURIComponent(q)}`,
+ `fq=-publish_b:false AND price_tier1_v2_f:[1 TO *] AND product_rating_f:[8 TO *]`,
+ `rows=100`, // Request maximum 100 rows per chunk (100 IDs per chunk)
+ `start=0`,
+ `sort=${paramOrderBy}`,
+ ];
+
+ const solrUrl =
+ process.env.SOLR_HOST +
+ '/solr/product/select?' +
+ queryParams.join('&');
+
+ console.log(
+ `[SEARCHKEY BATCH QUERY] Chunk: ${chunk.slice(0, 5).join(',')}...`,
+ );
+
+ return axios(solrUrl).catch((error) => {
+ console.error('[SEARCHKEY BATCH ERROR]', error.message);
+ throw error;
+ });
+ });
+
+ // Wait for all queries to complete
+ const batchResults = await Promise.all(batchQueries);
+
+ // Merge all documents from all chunks, removing duplicates
+ const allDocs = mergeSolrResults(
+ batchResults.map((r) => r.data.response.docs),
+ );
+
+ console.log(
+ `[SEARCHKEY MERGE] Merged ${allDocs.length} unique documents from ${batchResults.length} chunks`,
+ );
+
+ // Apply pagination on merged results
+ const paginatedDocs = allDocs.slice(offset, offset + limitNum);
+
+ // Use first result's response structure as template
+ const templateResponse = batchResults[0].data;
+
+ const mergedResponse = {
+ ...templateResponse,
+ response: {
+ ...templateResponse.response,
+ numFound: allDocs.length,
+ start: offset,
+ rows: limitNum,
+ docs: paginatedDocs,
+ },
+ responseHeader: {
+ ...templateResponse.responseHeader,
+ params: {
+ ...templateResponse.responseHeader.params,
+ start: offset,
+ rows: limitNum,
+ },
+ },
+ };
+
+ mergedResponse.response.products = productMappingSolr(
+ paginatedDocs,
auth?.pricelist || false,
);
- delete result.data.response.docs;
- result.data = camelcaseObjectDeep(result.data);
+ delete mergedResponse.response.docs;
+ mergedResponse.data = camelcaseObjectDeep(mergedResponse);
- return res.status(200).json(result.data);
+ return res.status(200).json(mergedResponse.data);
} catch (e) {
+ console.error('[SEARCHKEY ERROR]', e.message);
return res.status(400).json({ error: e.message });
}
}