@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)
346 lines • 16.1 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 console_1 = require("console");
const fs = require("fs");
const __1 = require("../..");
const asset_models_1 = require("../../api/sdk/asset/asset-models");
const command_utils_1 = require("./command-utils");
const path = require("path");
let color = (0, command_utils_1.getColor)("magenta");
const trimLeft = (str, charlist) => {
if (charlist === undefined)
charlist = "s";
return str.replace(new RegExp("^[" + charlist + "]+"), "");
};
function getLength(dataType, options) {
if (dataType === "STRING")
return parseInt(options.length);
if (dataType === "BIG_STRING")
return parseInt(options.biglength);
return null;
}
function toMindSphereDataType(schemaProperty, options) {
let result = undefined;
(0, command_utils_1.verboseLog)(JSON.stringify(schemaProperty), options.verbose);
if (!schemaProperty.type) {
console.log("Invalid property in Schema");
console.log(JSON.stringify(schemaProperty));
}
switch (schemaProperty.type.toLowerCase()) {
case "integer":
result = "INT";
break;
case "number":
result = "DOUBLE";
break;
case "boolean":
result = "BOOLEAN";
break;
case "array":
result = "BIG_STRING";
break;
case "string":
result = schemaProperty.format === "date-time" ? "TIMESTAMP" : "STRING";
break;
default:
throw new Error(`Unsupported Type ${JSON.stringify(schemaProperty)}`);
}
return result;
}
exports.default = (program) => {
program
.command("aspects")
.alias("asp")
.option("-m, --mode [list|create|delete|convert|template|info]", "list | create | delete | convert | template | info", "list")
.option("-f, --file <file>", ".mdsp.json file with aspect type definition")
.option("-s, --schema <schema>", "JSON Schema")
.option("-n, --aspect <aspect>", "the aspect type name")
.option("-p, --prefixflattened", "prefix variable names with previous name when flattening schema")
.option("-t, --targetonly", "consider only variables which have target equal to aspect in schema")
.option("-u, --untargeted", "consider only variables which don't have target in schema")
.option("-l, --length <length>", "default string length", "255")
.option("-b, --biglength <biglength>", "default bigstring length", "5000")
.option("-i, --idonly", "list only ids")
.option("-c, --includeshared", "include shared aspect types")
.option("-k, --passkey <passkey>", "passkey")
.option("-y, --retry <number>", "retry attempts before giving up", "3")
.option("-v, --verbose", "verbose output")
.description(color("list, create or delete aspects *"))
.action((options) => {
(() => __awaiter(void 0, void 0, void 0, function* () {
try {
checkRequiredParamaters(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 "convert":
const aspectType = convertAspectType(options);
(0, command_utils_1.verboseLog)(aspectType, options.verbose);
writeAspectTypeToFile(options, aspectType);
break;
case "list":
yield listAspectTypes(sdk, options);
break;
case "template":
createTemplate(options);
console.log("Edit the file before submitting it to mindsphere.");
break;
case "delete":
yield deleteAspectType(options, sdk);
break;
case "create":
yield createAspectType(options, sdk);
break;
case "info":
yield aspectTypeInfo(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 aspects --mode list \t\t\t\t\t list all aspect types`);
(0, console_1.log)(` mdsp aspects --mode list --aspect Environment\t\t list all aspect types which are named Environment`);
(0, console_1.log)(` mdsp aspects --mode template --aspect Environment \n\tcreate a template file (Enironment.aspect.mdsp.json) for aspect Environment`);
(0, console_1.log)(` mdsp aspects --mode create --file Environment.aspects.mdsp.json \n\tcreate aspect type Environment in MindSphere`);
(0, console_1.log)(` mdsp aspects --mode convert --schema Environment.schema.json --aspect Environment \n\t create a template file for aspect type Environment from JSON schema`);
(0, console_1.log)(` mdsp aspects --mode convert --schema Environment.schema.json --aspect Environment --prefixflattened \n\t prefixes the variable names with parent object names (e.g. Environment_Temperature)`);
(0, console_1.log)(` mdsp aspects --mode convert --schema Environment.schema.json --aspect Environment --targetonly \n\t select only variables from json schema with target property equal to assettype`);
(0, command_utils_1.serviceCredentialLog)();
});
};
function createAspectType(options, sdk) {
return __awaiter(this, void 0, void 0, function* () {
const filePath = path.resolve(options.file);
const file = fs.readFileSync(filePath);
const aspect = JSON.parse(file.toString());
const includeShared = options.includeshared;
const name = aspect.name.includes(".") ? aspect.name : `${sdk.GetTenant()}.${aspect.name}`;
yield sdk.GetAssetManagementClient().PutAspectType(name, aspect, { includeShared: includeShared });
console.log(`creted aspect ${color(name)}`);
});
}
function createTemplate(options) {
const templateType = {
name: options.aspect,
category: asset_models_1.AssetManagementModels.AspectResource.CategoryEnum.Dynamic,
scope: asset_models_1.AssetManagementModels.AspectType.ScopeEnum.Private,
description: "generated by MindSphere CLI",
variables: [
{
name: "var1",
dataType: "BOOLEAN",
unit: ".",
searchable: true,
length: null,
qualityCode: true,
},
{
name: "var2",
dataType: "INT",
unit: ".",
searchable: true,
length: null,
qualityCode: true,
},
{
name: "var3",
dataType: "DOUBLE",
unit: ".",
searchable: true,
length: null,
qualityCode: true,
},
{
name: "var4",
dataType: "STRING",
unit: ".",
searchable: true,
length: 255,
qualityCode: true,
},
{
name: "var5",
dataType: "BIG_STRING",
unit: ".",
searchable: true,
length: 1000,
qualityCode: true,
},
{
name: "var6",
dataType: "TIMESTAMP",
unit: ".",
searchable: true,
length: null,
qualityCode: true,
},
],
};
(0, command_utils_1.verboseLog)(JSON.stringify(templateType, null, 2), options.verbose);
writeAspectTypeToFile(options, templateType);
}
function writeAspectTypeToFile(options, aspectType) {
const fileName = options.file || `${options.aspect}.aspect.mdsp.json`;
fs.writeFileSync(fileName, JSON.stringify(aspectType, null, 2));
console.log(`The data was written into ${color(fileName)} run \n\n\t mdsp aspects --mode create --file ${fileName} \n\nto create the aspect`);
}
function deleteAspectType(options, sdk) {
return __awaiter(this, void 0, void 0, function* () {
const includeShared = options.includeshared;
const id = options.aspect.includes(".") ? options.aspect : `${sdk.GetTenant()}.${options.aspect}`;
const aspType = yield sdk.GetAssetManagementClient().GetAspectType(id, { includeShared: includeShared });
yield sdk.GetAssetManagementClient().DeleteAspectType(id, { ifMatch: aspType.etag, includeShared: includeShared });
console.log(`Aspect with id ${color(id)} deleted.`);
});
}
function convertAspectType(options) {
const schemaPath = path.resolve(options.schema);
const inputSchemaBuffer = fs.readFileSync(schemaPath).toString();
const inputSchema = JSON.parse(inputSchemaBuffer);
const variables = [];
generateVariables("", inputSchema, options, variables);
const aspectType = {
name: options.aspect,
category: asset_models_1.AssetManagementModels.AspectResource.CategoryEnum.Dynamic,
scope: asset_models_1.AssetManagementModels.AspectType.ScopeEnum.Private,
description: inputSchema.description || ("source:" + options.schema).substr(0, 100),
variables: variables,
};
return aspectType;
}
function listAspectTypes(sdk, options) {
return __awaiter(this, void 0, void 0, function* () {
var _a;
const includeShared = options.includeshared;
const assetMgmt = sdk.GetAssetManagementClient();
let page = 0;
let aspects;
const filter = buildFilter(options);
(0, command_utils_1.verboseLog)(JSON.stringify(filter, null, 2), options.verbose);
!options.idonly && console.log(`id etag type variables name\tsharing`);
let assetCount = 0;
do {
aspects = (yield (0, __1.retry)(options.retry, () => assetMgmt.GetAspectTypes({
page: page,
size: 100,
filter: Object.keys(filter).length === 0 ? undefined : JSON.stringify(filter),
sort: "id,asc",
includeShared: includeShared,
})));
aspects._embedded = aspects._embedded || { aspectTypes: [] };
aspects.page = aspects.page || { totalPages: 0 };
for (const aspect of aspects._embedded.aspectTypes || []) {
assetCount++;
!options.idonly &&
console.log(`${aspect.id}\t${aspect.etag} ${aspect.category} [${aspect.variables.length}]\t${color(aspect.name)}\t${(_a = aspect.sharing) === null || _a === void 0 ? void 0 : _a.modes}`);
options.idonly && console.log(`${aspect.id}`);
(0, command_utils_1.verboseLog)(JSON.stringify(aspect, null, 2), options.verbose);
}
} while (page++ < (aspects.page.totalPages || 0));
console.log(`${color(assetCount)} aspects listed.\n`);
});
}
function buildFilter(options) {
const filter = (options.filter && JSON.parse(options.filter)) || {};
let pointer = filter;
if (options.aspect !== undefined) {
filter.and = {};
pointer = filter.and;
}
if (options.aspect) {
pointer.id = { contains: `${options.aspect}` };
}
if (options.typeid) {
pointer.id = { contains: `${options.typeid}` };
}
return filter;
}
function generateVariables(prefix, inputSchema, options, variables) {
for (const key in inputSchema.properties) {
const obj = inputSchema.properties[key];
if (obj.type !== "object") {
const type = toMindSphereDataType(obj, options);
// helper to deal with targets being string or string[]
const isTarget = (aspect, target) => {
if (!target) {
return false;
}
else {
const targets = target instanceof Array ? target : [target];
return targets.includes(aspect);
}
};
// only targeted properties
if (options.targetonly && !isTarget(options.aspect, obj.target))
continue;
if (options.untargeted && isTarget(options.aspect, obj.target))
continue;
let name = options.prefixflattened ? `${prefix}_${key}` : key;
const originalName = name;
name = name.replace(" ", "_");
name = name.replace("-", "_");
name = name.replace(/[\W_]/g, "_");
name = name.trim();
name = trimLeft(name, "_");
if (name !== originalName) {
console.log(`replaced ${originalName} with ${name}`);
}
const variable = {
name: name,
dataType: type,
unit: obj.unit || ".",
searchable: type !== "BIG_STRING",
length: getLength(type, options),
qualityCode: true,
};
variables.push(variable);
}
else {
generateVariables(options.prefixflattened ? `${prefix}_${key}` : "", obj, options, variables);
}
}
}
function aspectTypeInfo(options, sdk) {
return __awaiter(this, void 0, void 0, function* () {
const includeShared = options.includeshared;
const id = options.aspect.includes(".") ? options.aspect : `${sdk.GetTenant()}.${options.aspect}`;
const aspType = yield sdk.GetAssetManagementClient().GetAspectType(id, { includeShared: includeShared });
console.log(JSON.stringify(aspType, null, 2));
});
}
function checkRequiredParamaters(options) {
options.mode === "template" &&
!options.aspect &&
(0, command_utils_1.errorLog)("you have to provide aspect type to create a template (see mdsp aspects --help for more details)", true);
options.mode === "create" &&
!options.file &&
(0, command_utils_1.errorLog)("you have to provide a file with aspect type to create an aspect type (see mdsp aspects --help for more details)", true);
options.mode === "delete" &&
!options.aspect &&
(0, command_utils_1.errorLog)("you have to provide the aspect type to delete (see mdsp aspects --help for more details)", true);
options.mode === "convert" &&
!options.schema &&
(0, command_utils_1.errorLog)("you have to provide the json schema to convert (see mdsp aspects --help for more details)", true);
options.mode === "convert" &&
!options.aspect &&
(0, command_utils_1.errorLog)("you have to provide the aspect name for the schema (see mdsp aspects --help for more details)", true);
}
//# sourceMappingURL=aspect-commands.js.map