@mindconnect/mindconnect-nodejs
Version:
NodeJS Library for Siemens Insights Hub Connectivity - TypeScript SDK for Insights Hub and Industrial IoT - Command Line Interface - Insights Hub Development Proxy (Siemens Insights Hub was formerly known as MindSphere)
161 lines • 9.28 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 });
exports.createFilter = void 0;
const console_1 = require("console");
const fs = require("fs");
const path = require("path");
const test_utils_1 = require("../../../test/test-utils");
const utils_1 = require("../../api/utils");
const command_utils_1 = require("./command-utils");
const ora = require("ora-classic");
let color = (0, command_utils_1.getColor)("magenta");
exports.default = (program) => {
program
.command("events-bulk")
.alias("dn")
.alias("download-events")
.option("-m, --mode [download|template|delete|check]", "mode [download | template | delete | check]", "download")
.option("-d, --dir <dir>", "download folder", "eventdownload")
.option("-i, --assetid <assetid>", "mindsphere asset id ")
.option("-j, --jobid <jobid>", "check deletion process of jobs with jobid")
.option("-f, --filter [filter]", `JSON file with filter (see: ${color("https://developer.mindsphere.io/apis/advanced-eventmanagement/api-eventmanagement-best-practices.html")}) `)
.option("-s, --size <size>", "max entries per file ", "100")
.option("-t, --sort <sort>", "sort events ", "timestamp,asc")
.option("-p, --passkey <passkey>", `passkey`)
.option("-y, --retry <number>", "retry attempts before giving up", "3")
.option("-v, --verbose", "verbose output")
.description(`${color("download or delete the events in bulk *")}`)
.action((options) => {
(() => __awaiter(void 0, void 0, void 0, function* () {
try {
checkParameters(options);
const sdk = (0, command_utils_1.getSdk)(options);
color = (0, command_utils_1.adjustColor)(color, options);
(0, command_utils_1.homeDirLog)(options.verbose, color);
(0, command_utils_1.proxyLog)(options.verbose, color);
switch (options.mode) {
case "download":
yield downloadEvents(options, sdk);
break;
case "template":
createFilter(options);
break;
case "delete":
yield deleteEvents(options, sdk);
break;
case "check":
yield checkDeleteJob(options, sdk);
break;
default:
throw Error(`no such option: ${options.mode}`);
}
}
catch (err) {
(0, command_utils_1.errorLog)(err, options.verbose);
}
}))();
})
.on("--help", () => {
(0, console_1.log)("\n Examples:\n");
(0, console_1.log)(` mdsp events-bulk --mode download --asssetid 1234567..ef \t download events from specified asset`);
(0, console_1.log)(` mdsp events-bulk --mode download --dir newdir \t\t download last 7 days of events to <dir> folder`);
(0, console_1.log)(` mdsp events-bulk --mode template --assetid 1234576..ef \t create template file event.filter.mdsp.json`);
(0, console_1.log)(` mdsp events-bulk --mode download --filter event.filter.mdsp.json \t\t download events using configured filter`);
(0, console_1.log)(` mdsp events-bulk --mode delete --filter event.filter.mdsp.json \t\t delete events using configured filter`);
(0, console_1.log)(` mdsp events-bulk --mode check --jobid <jobid> \t\t check the state of bulk deleting job`);
(0, command_utils_1.serviceCredentialLog)();
});
};
function downloadEvents(options, sdk) {
return __awaiter(this, void 0, void 0, function* () {
var _a;
fs.mkdirSync(path.resolve(options.dir));
const eventManagement = sdk.GetEventManagementClient();
const spinner = ora("downloading mindsphere events");
!options.verbose && spinner.start();
let filter;
if (options.filter) {
const filterPath = path.resolve(options.filter);
filter = fs.readFileSync(filterPath).toString();
}
if (!options.filter && options.assetid) {
filter = JSON.stringify({ entityId: options.assetid });
}
const result = yield (0, utils_1.retry)(options.retry, () => eventManagement.GetEvents({ size: options.size, filter: filter, sort: options.sort }));
(0, command_utils_1.verboseLog)(`downloading events_0.json`, options.verbose, spinner);
fs.writeFileSync(`${path.resolve(options.dir)}/events_0.json`, JSON.stringify(result._embedded));
yield (0, test_utils_1.sleep)(500);
for (let index = 1; index < (((_a = result.page) === null || _a === void 0 ? void 0 : _a.totalPages) || 0); index++) {
const next = yield (0, utils_1.retry)(options.retry, () => eventManagement.GetEvents({ size: result.page.size, page: index }));
(0, command_utils_1.verboseLog)(`downloading events_${index}.json`, options.verbose, spinner);
fs.writeFileSync(`${path.resolve(options.dir)}/events_${index}.json`, JSON.stringify(next._embedded));
yield (0, test_utils_1.sleep)(500);
}
!options.verbose && spinner.succeed("Done");
console.log(`Files with event data are in ${color(path.resolve(options.dir))} directory`);
});
}
function deleteEvents(options, sdk) {
return __awaiter(this, void 0, void 0, function* () {
const eventManagement = sdk.GetEventManagementClient();
let filter;
if (options.filter) {
const filterPath = path.resolve(options.filter);
filter = JSON.parse(fs.readFileSync(filterPath).toString());
}
if (!options.filter && options.assetid) {
filter = { entityId: options.assetid };
}
const result = yield (0, utils_1.retry)(options.retry, () => eventManagement.PostDeleteEventsJob({ filter: filter }));
console.log(`Deletion job with id ${color(result.id)} is in state ${color(result.state)}.`);
result.details && console.log(`Details: ${JSON.stringify(result.details)}.`);
console.log(`Run\n\n\tmdsp events-bulk --mode check --jobid ${result.id}\n\nto check the state of the job.\n `);
});
}
function checkDeleteJob(options, sdk) {
return __awaiter(this, void 0, void 0, function* () {
const eventManagement = sdk.GetEventManagementClient();
const result = (yield (0, utils_1.retry)(options.retry, () => eventManagement.GetDeleteEventsJob(options.jobid)));
console.log(`Deletion job with id ${color(result.id)} is in state ${color(result.state)}.`);
result.details && console.log(`Details: ${JSON.stringify(result.details)}.\n`);
});
}
function createFilter(options) {
const now = new Date();
const sevenDaysAgo = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
const template = {
timestamp: {
between: `[${sevenDaysAgo.toISOString()},${now.toISOString()})`,
},
entityId: options.assetid || "<enter asset id>",
typeId: options.eventtype || "com.siemens.mindsphere.eventmgmt.event.type.MindSphereStandardEvent",
};
const pathString = options.filter || `event.filter.mdsp.json`;
const resolvedPath = path.resolve(pathString);
fs.writeFileSync(resolvedPath, JSON.stringify(template, null, 2));
console.log(`The filter was written into ${color(resolvedPath)} run \n\n\tmdsp events-bulk --mode download --filter ${pathString} \t ${color(" to download events")}`);
console.log(`\tmdsp events-bulk --mode delete --filter ${pathString} \t ${color(" to delete events")}`);
console.log(`\tmdsp events --mode list --filter ${pathString} \t\t ${color(" to list events")}`);
console.log("\nEdit the filter before downloading or deleting the events.");
}
exports.createFilter = createFilter;
function checkParameters(options) {
!options.dir &&
(0, command_utils_1.errorLog)("Missing dir name for events-bulk command. Run mdsp dn --help for full syntax and examples.", true);
options.mode === "delete" &&
!options.filter &&
(0, command_utils_1.errorLog)("You must specifify a filter when deleting the events. Create one with mdsp events-bulk --mode template.", true);
options.mode === "check" &&
!options.jobid &&
(0, command_utils_1.errorLog)("You have to specify the jobid for the delete command", true);
}
//# sourceMappingURL=download-events.js.map