import callerId from 'caller-id';
import { cleanupData, ShopIdService } from 'cpb-api';
import { File, LSD } from 'cpb-storage';
import { accumulator, getProductIdsFromFiles, groupFiles } from '../common/index.js';
/**
* @description
* ### Get and categorize the storage bucket files for the given filestore
* @method module:cpb-api/filestore.get
* @async
* @param {?string} [bucket=process.env.BUCKET || 'custom-product-builder'] - gce storage bucket
* @param {string|number} id - filestore id
* @param {!string|number} [shop_id=:id] - filestore id
* @param {?boolean} [versions=true] - include file versions
* @param {?boolean} [fetch=false] - fetch new data and update index
* @param {?boolean} [files=false] - include files array to the output
* @returns {Store}
*/
export default async function get({
fetch = false,
files = false,
versions = true,
bucket = process.env.BUCKET || 'custom-product-builder',
id,
shop_id = id,
}) {
// const caller = callerId.getData();
if (!shop_id) throw new TypeError(`[cpb-api/filestore.get] ERROR_NO_SHOP_ID.${callerId.getDetailedString()}`);
// title(`[cpb-api/filestore.get][${shopID},${shopName}]`, { shop_id, bucket, versions, fetch });
function out(data, props = { files, versions, deletedFiles: files }) {
return cleanupData(data, props);
}
if (!fetch) {
try {
const data = await File.read({ bucket, name: `${shop_id}/index.json` });
return out(data);
} catch (e) {
console.error('[api/filestore/get] readfile error', e.code, e.message, callerId.getDetailedString());
}
}
// console.debug(result);
// getting list of productIds
const { id: shopID, name: shopName } = await ShopIdService.getIdName(shop_id),
prefix = `${shopID || shop_id}/`,
result = await LSD({
bucket,
prefix,
versions,
}),
[storeFiles, deletedFiles, productConfigs] = groupFiles(result.files, true),
[products] = getProductIdsFromFiles(storeFiles),
[, deletedProducts] = getProductIdsFromFiles(deletedFiles),
retval = {
id: +(shopID || shop_id),
shopName,
indexFileGS: `gs://${bucket}/${prefix}index.json`,
indexFileWeb: `https://storage.googleapis.com/${bucket}/${shopID || shop_id}/index.json`,
dir: prefix,
versions,
bucket,
productIds: products,
deletedProducts,
productConfigs,
stats: {
products: products.length,
deletedProducts: deletedProducts.length,
},
};
// if (files) {
retval.files = storeFiles;
retval.deletedFiles = deletedFiles;
retval.stats = {
...retval.stats,
files: storeFiles.length,
deletedFiles: deletedFiles.length,
size: storeFiles.map(f => +f.totalSize).reduce(accumulator, 0),
deletedFileSize: deletedFiles.map(f => +f.totalSize).reduce(accumulator, 0),
previousFileVersionsSize: storeFiles.map(f => +f.previousFileVersionsSize).reduce(accumulator, 0),
previousFileVersionsCount: storeFiles.map(f => +f.previousFileVersionsCount).reduce(accumulator, 0),
};
// }
// saving file
File.upload({ bucket, name: `${id}/index.json`, data: retval })
.then(console.info)
.catch(console.error);
return out(retval);
}