@archer-edu/dxp-directus-cli
Version:
215 lines • 8.35 kB
JavaScript
;
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
const api_1 = require("./support/api");
const config_1 = require("./support/config");
const LIMIT = 100;
const register = (program) => {
program
.command("promote-version <siteId> <tag>")
.description("Promote a site's versioned blogs and pages to main for the provided tag")
.option("-d, --debug", "Enable debug mode")
.option("-T, --token <token>", "Directus API token used for promotion")
.action((siteId, tag, options) => __awaiter(void 0, void 0, void 0, function* () {
const { debug, token } = options;
yield promoteSiteVersion({ siteId, tag, debug, token });
}));
};
exports.default = register;
function promoteSiteVersion({ siteId, tag, debug, token }) {
return __awaiter(this, void 0, void 0, function* () {
if (!tag || tag === "main") {
console.error("A non-main version tag must be provided");
process.exitCode = 1;
return;
}
const authToken = token || process.env.DIRECTUS_TOKEN;
if (!authToken) {
console.error("A Directus token is required. Pass --token or set DIRECTUS_TOKEN.");
process.exitCode = 1;
return;
}
if (debug) {
console.log(`Promoting version '${tag}' for site '${siteId}'`);
}
const entryIds = yield getSiteEntryIds(siteId, debug);
const pageIds = yield getSitePageIds(siteId, debug);
if (debug) {
console.log(`Found ${entryIds.length} blog entries and ${pageIds.length} pages for site ${siteId}`);
}
const entrySummary = yield promoteCollection({
collection: "site_entry",
ids: entryIds,
tag,
label: "blog entry",
debug,
token: authToken
});
const pageSummary = yield promoteCollection({
collection: "site_pages",
ids: pageIds,
tag,
label: "page",
debug,
token: authToken
});
reportSummary(entrySummary, pageSummary);
});
}
function getSiteEntryIds(siteId, debug) {
return __awaiter(this, void 0, void 0, function* () {
return fetchPaginatedIds(siteId, debug, postsQuery, "entries");
});
}
function getSitePageIds(siteId, debug) {
return __awaiter(this, void 0, void 0, function* () {
return fetchPaginatedIds(siteId, debug, pagesQuery, "pages");
});
}
function fetchPaginatedIds(siteId, debug, queryBuilder, key) {
return __awaiter(this, void 0, void 0, function* () {
let offset = 0;
const ids = [];
let hasMore = true;
while (hasMore) {
const query = queryBuilder(siteId, LIMIT, offset);
const result = yield (0, api_1.graphRequest)(config_1.queryPath, query, debug);
const items = ((result === null || result === void 0 ? void 0 : result[key]) || []);
ids.push(...items.map(item => item.id));
if (debug)
console.log(`Fetched ${items.length} ${key} at offset ${offset}`);
if (items.length < LIMIT) {
hasMore = false;
}
else {
offset += LIMIT;
}
}
return ids;
});
}
function promoteCollection({ collection, ids, tag, label, debug, token }) {
return __awaiter(this, void 0, void 0, function* () {
const summary = {
label,
total: ids.length,
matching: 0,
promoted: 0,
skipped: 0,
failures: []
};
for (const id of ids) {
try {
const targetVersion = yield getVersion(collection, id, tag, token, debug);
if (!targetVersion) {
summary.skipped += 1;
continue;
}
summary.matching += 1;
if (debug) {
console.log(`Promoting ${label} ${id} to main from version ${tag}`);
}
const mainHash = yield getMainHash(targetVersion.id, token, debug);
yield (0, api_1.directusRequest)(`/versions/${encodeURIComponent(targetVersion.id)}/promote`, {
method: "POST",
headers: Object.assign({ "Content-Type": "application/json" }, authHeader(token)),
body: JSON.stringify({ mainHash }),
debug
});
summary.promoted += 1;
}
catch (error) {
const message = error.message || "Unknown error";
summary.failures.push({ id, message });
if (debug) {
console.error(`Failed to promote ${label} ${id}: ${message}`);
}
}
}
return summary;
});
}
function getVersion(collection, id, tag, token, debug) {
var _a;
return __awaiter(this, void 0, void 0, function* () {
const params = new URLSearchParams();
params.append('filter[collection][_eq]', collection);
params.append('filter[item][_eq]', id);
params.append('filter[key][_eq]', tag);
params.append('limit', '1');
params.append('fields', 'id,key,collection,item');
const response = yield (0, api_1.directusRequest)(`/versions?${params.toString()}`, {
debug,
headers: authHeader(token)
});
return (_a = response === null || response === void 0 ? void 0 : response.data) === null || _a === void 0 ? void 0 : _a[0];
});
}
function getMainHash(versionId, token, debug) {
var _a;
return __awaiter(this, void 0, void 0, function* () {
const response = yield (0, api_1.directusRequest)(`/versions/${encodeURIComponent(versionId)}/compare`, {
debug,
headers: authHeader(token)
});
const hash = (_a = response === null || response === void 0 ? void 0 : response.data) === null || _a === void 0 ? void 0 : _a.mainHash;
if (!hash)
throw new Error("Main hash not returned from compare endpoint");
return hash;
});
}
function authHeader(token) {
return token ? { Authorization: `Bearer ${token}` } : {};
}
function reportSummary(blogSummary, pageSummary) {
const summaries = [blogSummary, pageSummary];
summaries.forEach(({ label, total, matching, promoted, skipped, failures }) => {
console.log([
`${label}:`,
`total=${total}`,
`matched=${matching}`,
`promoted=${promoted}`,
`skipped=${skipped}`,
`failed=${failures.length}`
].join(" "));
});
const failures = summaries.flatMap(summary => summary.failures.map(failure => (Object.assign({ label: summary.label }, failure))));
if (failures.length > 0) {
console.error("Failures:");
failures.forEach(({ label, id, message }) => {
console.error(` - ${label} ${id}: ${message}`);
});
process.exitCode = 1;
}
else {
console.log("Version promotion complete");
}
}
const postsQuery = (siteId, limit, offset) => `{
entries: site_entry(
filter: { site_id: { key: { _eq: "${siteId}" }}},
limit: ${limit},
offset: ${offset}
) {
id
}
}`;
const pagesQuery = (siteId, limit, offset) => `{
pages: site_pages (
filter: { site: { key: { _eq: "${siteId}"}}},
sort:["sort"],
limit: ${limit},
offset: ${offset}
) {
id
}
}`;
//# sourceMappingURL=promote-version.js.map