Skip to content

Commit

Permalink
Update event.controller.js
Browse files Browse the repository at this point in the history
  • Loading branch information
leungkinghin-ct committed Aug 14, 2023
1 parent 9b698e8 commit e6eea6f
Showing 1 changed file with 41 additions and 19 deletions.
60 changes: 41 additions & 19 deletions full-ingestion/src/controllers/event.controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ import { createApiRoot } from '../clients/create.client.js';
import CustomError from '../errors/custom.error.js';
import { default as saveProducts } from '../extensions/algolia-example/clients/client.js';

const CHUNK_SIZE = 100;

async function syncProducts(storeKey) {
const products = await getProductsByStore(storeKey);

Expand All @@ -12,25 +14,45 @@ async function syncProducts(storeKey) {
}

async function getProductsByStore(storeKey) {
return await createApiRoot()
.inStoreKeyWithStoreKeyValue({ storeKey: Buffer.from(storeKey).toString() })
.productSelectionAssignments()
.get({
queryArgs: {
expand: [
'product',
'product.productType',
'product.taxCategory',
'product.masterData.current.categories[*]',
],
},
})
.execute()
.then((response) => response.body.results)
.then((results) => results.map((result) => result.product))
.catch((error) => {
throw new CustomError(400, `Bad request: ${error.message}`, error);
});
let lastProductId = undefined;
let hasNextQuery = true;
let allProducts = [];

while (hasNextQuery) {
let queryArgs = {
limit: CHUNK_SIZE,
withTotal: false,
sort: 'product.id asc',
expand: [
'product',
'product.productType',
'product.taxCategory',
'product.masterData.current.categories[*]',
],
};
if (lastProductId) {
queryArgs.where = `product(id>"${lastProductId}")`;
}

let productChunk = await createApiRoot()
.inStoreKeyWithStoreKeyValue({
storeKey: Buffer.from(storeKey).toString(),
})
.productSelectionAssignments()
.get({ queryArgs })
.execute()
.then((response) => response.body.results)
.then((results) => results.map((result) => result.product))
.catch((error) => {
throw new CustomError(400, `Bad request: ${error.message}`, error);
});
hasNextQuery = productChunk.length == CHUNK_SIZE;
if (productChunk.length > 0) {
lastProductId = productChunk[productChunk.length - 1].id;
allProducts = allProducts.concat(productChunk);
}
}
return allProducts;
}

export const eventHandler = async (request, response) => {
Expand Down

0 comments on commit e6eea6f

Please sign in to comment.