@cn-shell3/netbox
Version:
cn-shell v3 extension for Netbox
112 lines (111 loc) • 3.22 kB
JavaScript
;
var __importDefault =
(this && this.__importDefault) ||
function (mod) {
return mod && mod.__esModule ? mod : { default: mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Netbox = void 0;
const cn_shell_1 = require("cn-shell");
const netbox_api_1 = require("./netbox-api");
const promises_1 = __importDefault(require("node:fs/promises"));
const CFG_NETBOX_SERVER = "NETBOX_SERVER";
const CFG_NETBOX_API_KEY = "NETBOX_API_KEY";
const CFG_DUMP_NETBOX_DATA = "DUMP_NETBOX_DATA";
const CFG_LOAD_NETBOX_DATA = "LOAD_NETBOX_DATA";
const CFG_NETBOX_DATA_DIR = "NETBOX_DATA_DIR";
const DEFAULT_NETBOX_CONFIG = {
dumpData: false,
loadData: false,
dataDir: "/tmp",
};
class Netbox extends cn_shell_1.ShellExt {
_server;
_apiKey;
_dumpData;
_loadData;
_dataDir;
constructor(shellConfig, passedConfig) {
super(shellConfig);
let config = {
...DEFAULT_NETBOX_CONFIG,
...passedConfig,
};
this._server = this.getConfigStr(CFG_NETBOX_SERVER, {
defaultVal: config.server,
});
this._apiKey = this.getConfigStr(CFG_NETBOX_API_KEY, {
defaultVal: config.apiKey,
redact: true,
});
this._dumpData = this.getConfigBool(CFG_DUMP_NETBOX_DATA, {
defaultVal: config.dataDir,
});
this._loadData = this.getConfigBool(CFG_LOAD_NETBOX_DATA, {
defaultVal: config.loadData,
});
this._dataDir = this.getConfigStr(CFG_NETBOX_DATA_DIR, {
defaultVal: config.dataDir,
});
}
async start() {
return true;
}
async stop() {
return;
}
async healthCheck() {
return true;
}
async get(group, resource, params, id) {
if (netbox_api_1.NetboxApi[group] === undefined) {
throw this.error(`'${group}' is not a valid group`);
}
if (netbox_api_1.NetboxApi[group][resource] === undefined) {
throw this.error(
`'${resource}' is not a valid resource in group '${group}'`,
);
}
let results = [];
if (this._loadData) {
let filePath = `${this._dataDir}/netbox-${group}-${resource}.json`;
this.debug("Loading netbox data from (%s)", filePath);
try {
results = JSON.parse(
await promises_1.default.readFile(filePath, { encoding: "utf8" }),
);
} catch (e) {
this.error("Path (%s) does not exist!", filePath);
}
return results;
}
let path = `${netbox_api_1.NetboxApi[group][resource]}`;
if (id !== undefined) {
path = `${path}/${id}`;
}
while (true) {
let res = await this.httpReq(this._server, path, {
method: "GET",
headers: {
Authorization: `Token ${this._apiKey}`,
},
searchParams: params,
});
let body = res.body;
results = results.concat(body.results);
if (body.next !== null) {
let parts = body.next.split("/api/");
path = `${this._server}/api/${parts[1]}`;
params = undefined;
continue;
}
break;
}
if (this._dumpData) {
this.debug("Dumping netbox data to (%s)", path);
await promises_1.default.writeFile(path, JSON.stringify(results));
}
return results;
}
}
exports.Netbox = Netbox;