@controlplane/cli
Version:
Control Plane Corporation CLI
76 lines • 2.6 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.fetchPages = fetchPages;
exports.fetchAllPages = fetchAllPages;
exports.applyMaxAndWarn = applyMaxAndWarn;
const links_1 = require("../util/links");
const format_1 = require("../util/format");
/**
* Fetches additional pages of results and warns if more are available.
*
* @param client - REST client for making API calls
* @param session - Session to get max from and emit warning
* @param result - The initial result to append pages to
*/
async function fetchPages(client, session, result) {
const max = session.format.max;
if (max === undefined) {
return;
}
let nextLink = (0, links_1.linksOf)(result).next;
while (true) {
if (!nextLink) {
break;
}
if (max > 0 && result.items.length >= max) {
break;
}
const nextPage = await client.get(nextLink);
result.items.splice(result.items.length, 0, ...nextPage.items);
nextLink = (0, links_1.linksOf)(nextPage).next;
// make the links of the main result valid in case someone want to continue iteration
result.links = nextPage.links;
}
if (max > 0) {
result.items = result.items.slice(0, max);
}
// Warn if there are more pages available
if (nextLink && max > 0) {
warnMoreRecords(session, max);
}
}
/**
* Fetches all pages of results without limit or warning.
*
* @param client - REST client for making API calls
* @param session - Session to use (max will be overridden to 0)
* @param result - The initial result to append pages to
*/
async function fetchAllPages(client, session, result) {
session.format.max = 0;
await fetchPages(client, session, result);
}
/**
* Applies max limit to items array and warns if there are more records.
*
* @param session - Session to get max from and emit warning
* @param items - Array of items to slice
* @returns The sliced items array
*/
function applyMaxAndWarn(session, items) {
const max = session.format.max;
if (!max || max < 1) {
return items;
}
const hasMore = items.length > max;
const sliced = items.slice(0, max);
if (hasMore) {
warnMoreRecords(session, max);
}
return sliced;
}
function warnMoreRecords(session, max) {
const defaultSuffix = max === format_1.DEFAULT_MAX ? ' (default)' : '';
session.pendingNotice = `Note: More records are available. Showing first ${max} results${defaultSuffix}. Use --max 0 to fetch all records.\n`;
}
//# sourceMappingURL=resultFetcher.js.map