UNPKG

@cn-shell3/netbox

Version:
103 lines (102 loc) 2.86 kB
import { ShellExt } from "cn-shell"; import { NetboxApi } from "./netbox-api"; import fsPromise from "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", }; export class Netbox extends 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 (NetboxApi[group] === undefined) { throw this.error(`'${group}' is not a valid group`); } if (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 fsPromise.readFile(filePath, { encoding: "utf8" }), ); } catch (e) { this.error("Path (%s) does not exist!", filePath); } return results; } let path = `${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 fsPromise.writeFile(path, JSON.stringify(results)); } return results; } }