import { title } from 'cpb-common';
import { File, LSD } from 'cpb-storage';
import { groupFiles } from '../common/index.js';
//import { cleanupData } from '../index.js';
/**
* @typedef {object} StoreSubscriptionData
* @property {string} [status='active'|'inactive] - subscription status
* @property {string} domain - filestore domain
* @property {string} fileName - subscription file name
* @property {?string[]} permissions
*/
const SUBSCRIPTION_BUCKETS = ['custom-product-builder-subscription-auth'];
/**
* @method module:cpb-api/subscription.list
* @description
* ### Lists The *Magento* Stores Subscriptions and creates index file
* @param {?string} [bucket='custom-product-builder-subscription-auth']
* @param {?boolean} [fetch=false] - fetch new data and update index file
* @param {?string} [name='index.json'] - index file name
* @param {?boolean} [versions=false] - include previous file versions
* @returns {Promise<{MagentoSubscriptionList}>}
*/
export default async function list({ bucket = 'custom-product-builder-subscription-auth', fetch = false, name = 'index.json', versions = false } = {}) {
const debug = {
bucket,
fetch,
name,
versions,
};
title('SubscriptionList', debug);
/**
* read subscription file data from the bucket
* @async
* @param {string} name - fileName
* @returns {Promise<{StoreSubscriptionData}>}
* @throws e
*/
async function readSubscriptionFile(name) {
let data;
try {
data = await File.read({ bucket, name });
} catch (e) {
console.error('ERROR.readSubscriptionFile', e);
throw e;
}
data.fileName = name;
return data;
}
if (!fetch) {
try {
return await File.read({ bucket, name });
} catch (e) {
console.error('ERROR.readSubscriptionFile', e);
}
}
try {
const data = await LSD({ bucket, versions });
const [files, deletedFiles] = groupFiles(data.files, versions);
/**
* @typedef {object} MagentoSubscriptionList
* @property {string} bucket - gce storage bucket
* @property {string[]} active - active subscriptions
* @property {string[]} inactive - inactive subscriptions
* @property {object[]} files - all files in bucket
* @property {object[]} deletedFiles - deleted files in bucket
* @property {object} debug - debug object
*/
/**
* @type {MagentoSubscriptionList}
*/
const result = {
bucket,
active: [],
inactive: [],
files,
deletedFiles,
debug,
};
for (const file of result.files) {
const fileData = await readSubscriptionFile(file.name);
if (fileData) {
fileData.fileName = file.name;
if (fileData.status === 'active') result.active.push(fileData);
else result.inactive.push(fileData);
}
}
File.upload({ bucket, name, data: result }).then(console.info).catch(console.error);
return result;
} catch (error) {
console.error({ error });
}
}