n8n-nodes-netbox
Version:
n8n community node for NetBox API integration with comprehensive DCIM, IPAM, Virtualization, Circuits, Wireless, and data center management operations
359 lines (358 loc) • 15.7 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.listVlans = listVlans;
exports.getVlanById = getVlanById;
exports.getVlanByName = getVlanByName;
exports.getVlanByVid = getVlanByVid;
exports.createVlan = createVlan;
exports.updateVlan = updateVlan;
exports.deleteVlan = deleteVlan;
exports.addTag = addTag;
exports.removeTag = removeTag;
const apiRequest_1 = require("../../../helpers/apiRequest");
const responseFormatter_1 = require("../../../helpers/responseFormatter");
const resourceLookup_1 = require("../../../helpers/resourceLookup");
async function listVlans() {
const returnAll = this.getNodeParameter('returnAll', 0);
const filters = this.getNodeParameter('filters', 0, {});
const qs = {};
Object.assign(qs, filters);
if (returnAll) {
const response = await apiRequest_1.apiRequestAllItems.call(this, 'GET', '/api/ipam/vlans/', {}, qs);
return responseFormatter_1.formatResponse.call(this, response);
}
else {
const limit = this.getNodeParameter('limit', 0);
qs.limit = limit;
const response = await apiRequest_1.apiRequest.call(this, 'GET', '/api/ipam/vlans/', {}, qs);
return responseFormatter_1.formatResponse.call(this, response);
}
}
async function getVlanById() {
const vlanId = this.getNodeParameter('vlanId', 0);
try {
const endpoint = `/api/ipam/vlans/${vlanId}/`;
const response = await apiRequest_1.apiRequest.call(this, 'GET', endpoint);
return responseFormatter_1.formatResponse.call(this, response);
}
catch (error) {
throw new Error(`Failed to get VLAN by ID: ${error.message}`);
}
}
async function getVlanByName() {
const vlanName = this.getNodeParameter('vlanName', 0);
try {
const endpoint = '/api/ipam/vlans/';
const query = { name: vlanName };
const response = await apiRequest_1.apiRequest.call(this, 'GET', endpoint, {}, query);
if (!response.results || response.results.length === 0) {
// Try name contains search
const queryContains = { name__ic: vlanName };
const responseContains = await apiRequest_1.apiRequest.call(this, 'GET', endpoint, {}, queryContains);
if (!responseContains.results || responseContains.results.length === 0) {
throw new Error(`VLAN with name "${vlanName}" not found`);
}
return responseFormatter_1.formatResponse.call(this, responseContains.results[0]);
}
return responseFormatter_1.formatResponse.call(this, response.results[0]);
}
catch (error) {
throw new Error(`Failed to get VLAN by name: ${error.message}`);
}
}
async function getVlanByVid() {
const vlanVid = this.getNodeParameter('vlanVid', 0);
try {
const endpoint = '/api/ipam/vlans/';
const query = { vid: vlanVid };
const response = await apiRequest_1.apiRequest.call(this, 'GET', endpoint, {}, query);
if (!response.results || response.results.length === 0) {
throw new Error(`VLAN with VID "${vlanVid}" not found`);
}
return responseFormatter_1.formatResponse.call(this, response.results[0]);
}
catch (error) {
throw new Error(`Failed to get VLAN by VID: ${error.message}`);
}
}
async function createVlan() {
const vid = this.getNodeParameter('vid', 0);
const name = this.getNodeParameter('vlanName', 0);
const status = this.getNodeParameter('status', 0);
const additionalFields = this.getNodeParameter('additionalFields', 0);
const body = {
vid,
name,
status,
};
try {
// Process additional fields that need lookup
if (additionalFields.group && isNaN(Number(additionalFields.group))) {
try {
additionalFields.group = await resourceLookup_1.lookupResourceByName.call(this, 'vlan-groups', additionalFields.group);
}
catch (error) {
throw new Error(`VLAN Group lookup failed: ${error.message}`);
}
}
if (additionalFields.site && isNaN(Number(additionalFields.site))) {
try {
additionalFields.site = await resourceLookup_1.lookupResourceByName.call(this, 'sites', additionalFields.site, 'dcim');
}
catch (error) {
throw new Error(`Site lookup failed: ${error.message}`);
}
}
if (additionalFields.tenant && isNaN(Number(additionalFields.tenant))) {
try {
additionalFields.tenant = await resourceLookup_1.lookupResourceByName.call(this, 'tenants', additionalFields.tenant, 'tenancy');
}
catch (error) {
throw new Error(`Tenant lookup failed: ${error.message}`);
}
}
if (additionalFields.role && isNaN(Number(additionalFields.role))) {
try {
additionalFields.role = await resourceLookup_1.lookupResourceByName.call(this, 'roles', additionalFields.role);
}
catch (error) {
throw new Error(`Role lookup failed: ${error.message}`);
}
}
// Process tags if they're provided as a string
if (additionalFields.tags && typeof additionalFields.tags === 'string') {
try {
const tagIds = [];
const tagNames = additionalFields.tags.split(',').map((tag) => tag.trim());
for (const tagName of tagNames) {
if (!isNaN(Number(tagName))) {
tagIds.push(Number(tagName));
}
else {
const tagId = await resourceLookup_1.lookupResourceByName.call(this, 'tags', tagName, 'extras');
tagIds.push(tagId);
}
}
additionalFields.tags = tagIds;
}
catch (error) {
throw new Error(`Tag lookup failed: ${error.message}`);
}
}
// Parse custom_fields if it's a string
if (additionalFields.custom_fields && typeof additionalFields.custom_fields === 'string') {
try {
additionalFields.custom_fields = JSON.parse(additionalFields.custom_fields);
}
catch (e) {
throw new Error(`Invalid JSON in custom_fields: ${e.message}`);
}
}
// Add all additional fields to the request body
Object.assign(body, additionalFields);
const endpoint = '/api/ipam/vlans/';
const response = await apiRequest_1.apiRequest.call(this, 'POST', endpoint, body);
return responseFormatter_1.formatResponse.call(this, response);
}
catch (error) {
throw new Error(`Failed to create VLAN: ${error.message}`);
}
}
async function updateVlan() {
let vlanId = this.getNodeParameter('vlanId', 0);
// Fallback to 'id' parameter if vlanId is not provided or is invalid
if (!vlanId || vlanId === 0 || isNaN(vlanId)) {
try {
vlanId = this.getNodeParameter('id', 0);
}
catch (error) {
// If neither parameter is available, throw an error
if (!vlanId || vlanId === 0 || isNaN(vlanId)) {
throw new Error('VLAN ID is required. Please provide either vlanId or id parameter.');
}
}
}
const updateFields = this.getNodeParameter('updateFields', 0);
try {
// Map prefixed field names to API field names
if (updateFields.vlanName) {
updateFields.name = updateFields.vlanName;
delete updateFields.vlanName;
}
if (updateFields.vlanDescription) {
updateFields.description = updateFields.vlanDescription;
delete updateFields.vlanDescription;
}
// Process fields that need lookup
if (updateFields.group && isNaN(Number(updateFields.group))) {
try {
updateFields.group = await resourceLookup_1.lookupResourceByName.call(this, 'vlan-groups', updateFields.group);
}
catch (error) {
throw new Error(`VLAN Group lookup failed: ${error.message}`);
}
}
if (updateFields.site && isNaN(Number(updateFields.site))) {
try {
updateFields.site = await resourceLookup_1.lookupResourceByName.call(this, 'sites', updateFields.site, 'dcim');
}
catch (error) {
throw new Error(`Site lookup failed: ${error.message}`);
}
}
if (updateFields.tenant && isNaN(Number(updateFields.tenant))) {
try {
updateFields.tenant = await resourceLookup_1.lookupResourceByName.call(this, 'tenants', updateFields.tenant, 'tenancy');
}
catch (error) {
throw new Error(`Tenant lookup failed: ${error.message}`);
}
}
if (updateFields.role && isNaN(Number(updateFields.role))) {
try {
updateFields.role = await resourceLookup_1.lookupResourceByName.call(this, 'roles', updateFields.role);
}
catch (error) {
throw new Error(`Role lookup failed: ${error.message}`);
}
}
// Process tags if they're provided as a string
if (updateFields.tags && typeof updateFields.tags === 'string') {
try {
const tagIds = [];
const tagNames = updateFields.tags.split(',').map((tag) => tag.trim());
for (const tagName of tagNames) {
if (!isNaN(Number(tagName))) {
tagIds.push(Number(tagName));
}
else {
const tagId = await resourceLookup_1.lookupResourceByName.call(this, 'tags', tagName, 'extras');
tagIds.push(tagId);
}
}
updateFields.tags = tagIds;
}
catch (error) {
throw new Error(`Tag lookup failed: ${error.message}`);
}
}
// Parse custom_fields if it's a string
if (updateFields.custom_fields && typeof updateFields.custom_fields === 'string') {
try {
updateFields.custom_fields = JSON.parse(updateFields.custom_fields);
}
catch (e) {
throw new Error(`Invalid JSON in custom_fields: ${e.message}`);
}
}
const endpoint = `/api/ipam/vlans/${vlanId}/`;
const response = await apiRequest_1.apiRequest.call(this, 'PATCH', endpoint, updateFields);
return responseFormatter_1.formatResponse.call(this, response);
}
catch (error) {
throw new Error(`Failed to update VLAN: ${error.message}`);
}
}
async function deleteVlan() {
const vlanId = this.getNodeParameter('vlanId', 0);
try {
const endpoint = `/api/ipam/vlans/${vlanId}/`;
await apiRequest_1.apiRequest.call(this, 'DELETE', endpoint);
return [{ json: { success: true } }];
}
catch (error) {
throw new Error(`Failed to delete VLAN: ${error.message}`);
}
}
async function addTag() {
const vlanId = this.getNodeParameter('vlanId', 0);
const tagIdentifier = this.getNodeParameter('tagIdentifier', 0);
try {
// Step 1: Get the Tag by identifier
let tagId;
if (!isNaN(Number(tagIdentifier))) {
tagId = Number(tagIdentifier);
}
else {
// Look up tag by name or slug
const tagEndpoint = '/api/extras/tags/';
let query = { name: tagIdentifier };
let response = await apiRequest_1.apiRequest.call(this, 'GET', tagEndpoint, {}, query);
// If no results, try slug
if (!response.results || response.results.length === 0) {
query = { slug: tagIdentifier };
response = await apiRequest_1.apiRequest.call(this, 'GET', tagEndpoint, {}, query);
}
if (!response.results || response.results.length === 0) {
throw new Error(`Tag "${tagIdentifier}" not found`);
}
tagId = response.results[0].id;
}
// Step 2: Get current VLAN details including existing tags
const vlanEndpoint = `/api/ipam/vlans/${vlanId}/`;
const vlanDetails = await apiRequest_1.apiRequest.call(this, 'GET', vlanEndpoint);
// Step 3: Check if tag is already present
const currentTagIds = vlanDetails.tags?.map((tag) => tag.id) || [];
if (currentTagIds.includes(tagId)) {
// Tag is already present, return current VLAN
return responseFormatter_1.formatResponse.call(this, vlanDetails);
}
// Step 4: Add tag to the list and update the VLAN
// IMPORTANT: We need to only send the tag IDs, not the full tag objects
currentTagIds.push(tagId);
const updateBody = {
tags: currentTagIds,
};
const updatedVlan = await apiRequest_1.apiRequest.call(this, 'PATCH', vlanEndpoint, updateBody);
return responseFormatter_1.formatResponse.call(this, updatedVlan);
}
catch (error) {
throw new Error(`Failed to add tag to VLAN: ${error.message}`);
}
}
async function removeTag() {
const vlanId = this.getNodeParameter('vlanId', 0);
const tagIdentifier = this.getNodeParameter('tagIdentifier', 0);
try {
// Step 1: Get the Tag by identifier
let tagId;
if (!isNaN(Number(tagIdentifier))) {
tagId = Number(tagIdentifier);
}
else {
// Look up tag by name or slug
const tagEndpoint = '/api/extras/tags/';
let query = { name: tagIdentifier };
let response = await apiRequest_1.apiRequest.call(this, 'GET', tagEndpoint, {}, query);
// If no results, try slug
if (!response.results || response.results.length === 0) {
query = { slug: tagIdentifier };
response = await apiRequest_1.apiRequest.call(this, 'GET', tagEndpoint, {}, query);
}
if (!response.results || response.results.length === 0) {
throw new Error(`Tag "${tagIdentifier}" not found`);
}
tagId = response.results[0].id;
}
// Step 2: Get current VLAN details including existing tags
const vlanEndpoint = `/api/ipam/vlans/${vlanId}/`;
const vlanDetails = await apiRequest_1.apiRequest.call(this, 'GET', vlanEndpoint);
// Step 3: Check if tag exists in VLAN tags
const currentTagIds = vlanDetails.tags?.map((tag) => tag.id) || [];
if (!currentTagIds.includes(tagId)) {
// Tag is not present, return current VLAN
return responseFormatter_1.formatResponse.call(this, vlanDetails);
}
// Step 4: Remove tag from the list and update the VLAN
// IMPORTANT: We need to only send the tag IDs, not the full tag objects
const updatedTagIds = currentTagIds.filter((id) => id !== tagId);
const updateBody = {
tags: updatedTagIds,
};
const updatedVlan = await apiRequest_1.apiRequest.call(this, 'PATCH', vlanEndpoint, updateBody);
return responseFormatter_1.formatResponse.call(this, updatedVlan);
}
catch (error) {
throw new Error(`Failed to remove tag from VLAN: ${error.message}`);
}
}