Skip to content

Instantly share code, notes, and snippets.

@ivansnag
Created April 18, 2024 15:36
Show Gist options
  • Save ivansnag/8cff1e42908bdab23cf1d91ff8c5a99c to your computer and use it in GitHub Desktop.
Save ivansnag/8cff1e42908bdab23cf1d91ff8c5a99c to your computer and use it in GitHub Desktop.
API script for creating services using the services.sync endpoint. Two output files will be created. One for error logging and one to map services to their reference_ids.
const fs = require('fs');
const csv = require('csv-parser');
const axios = require('axios');
const { v4: uuidv4 } = require('uuid');
const createCsvWriter = require('csv-writer').createObjectCsvWriter;
// Path to your CSV file
const csvFilePath = 'name_of_.csv';
const outputCsvFilePath = 'service_catalg_with_reference_id.csv';
// CSV Writer setup
const csvWriter = createCsvWriter({
path: outputCsvFilePath,
header: [
{id: 'reference_id', title: 'Reference ID'},
{id: 'name', title: 'Service Name'}
]
});
// URL of the services.sync API endpoint
const apiEndpoint = 'https://[YOUR INSTANCE NAME].getdx.net/api/services.sync';
// Your bearer token for API authentication
const bearerToken = 'YOUR-API-TOKEN';
// Function to make API request to create a service
async function createService(data) {
const referenceId = uuidv4(); // Generate a UUID for each service
try {
const response = await axios.post(apiEndpoint, {
reference_id: referenceId,
name: data.service
}, {
headers: {
'Accept': 'application/json',
'Authorization': `Bearer ${bearerToken}`,
'Content-Type': 'application/json'
}
});
console.log('Service created:', response.data);
// Write the service name and reference_id to another CSV
await csvWriter.writeRecords([{ reference_id: referenceId, name: data.service }]);
console.log('Service written to CSV:', { reference_id: referenceId, name: data.service });
} catch (error) {
console.error('Failed to create service:', error.message);
logError(error.message); // Log error to file
}
}
// Function to write errors to a log file
function logError(error) {
const timestamp = new Date().toISOString();
const errorMessage = `[${timestamp}] Error: ${error}\n`;
fs.appendFileSync('error_log.txt', errorMessage, 'utf8');
}
// Function to read and process the CSV file
function readAndProcessCsv(filePath) {
fs.createReadStream(filePath)
.pipe(csv())
.on('data', (row) => {
createService(row); // Call createService function for each row
})
.on('end', () => {
console.log('CSV file successfully processed');
});
}
// Call the function with the path to your CSV file
readAndProcessCsv(csvFilePath);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment