import { getBinaryFlagValue, stringifyJSON, title } from 'cpb-common';
import Store from '../filestore/index.js';
import app from '../index.js';
/**
* @method module:cpb-api/middleware.filestore
* @param {Request} req
* @param {Boolean|*} [req.query.fetch=0] - indicates whether to fetch data from the bucket or to return the data from
* the existing index file if present. If the file is not present the new data will be fetched and the index file
* will be created in order to ensure the fail-safe behavior
* @param {Boolean|*} [req.query.versions=0] - retrieve the previous file versions information in addition to the
* files.
* @param {Boolean|*} [req.query.files=1] - include the files array with version info into the output. If set to
* false the files and deletedFiles arrays will be omitted from the output.
* @param {Response} res
* @returns {Promise<void>}
*/
export default async function StoreMiddleware(req, res, next) {
if (req.method !== 'GET' && req.method !== 'HEAD') {
res.statusCode = req.method === 'OPTIONS' ? 200 : 405;
res.setHeader('Allow', 'GET, HEAD, OPTIONS');
res.setHeader('Content-Length', '0');
res.end();
return next();
}
// id = isNaN(+req.params.id) ? await Store.getIdFromName(req.params.id) : +req.params.id,
const bucket = app.get('bucket'),
// request query parameters
fetch = getBinaryFlagValue(req.query.fetch, 0),
versions = getBinaryFlagValue(req.query.versions, 1),
legacy = getBinaryFlagValue(req.query.legacy, 1),
misc = getBinaryFlagValue(req.query.misc, 1),
showFiles = getBinaryFlagValue(req.query.files, 0),
debug = {
bucket,
fetch,
versions,
showFiles,
misc,
legacy,
request: {
id: res.locals.rid,
query: req.query,
params: req.params,
locals: res.locals,
},
timestamp: new Date(),
};
let data,
status = 200;
try {
// if (typeof req.params.id !== 'undefined') {
if (res.locals.shopIdOrName) {
const { id, name } = res.locals.shop;
debug.id = id;
debug.name = name;
title(`[api/middleware/store][${id},${name}]`, debug);
data = await Store.get({ id, bucket, versions, fetch, files: showFiles });
} else
data = await Store.list({
bucket,
fetch,
versions,
legacy,
misc,
files: showFiles,
});
} catch (error) {
console.error('ERROR.StoreMiddleware', error);
status = 500;
data = error;
}
data.debug = debug;
res.type('json').status(status).end(stringifyJSON(data));
}