I am trying to import and delete large numbers of users from Okta while staying within rate limits, and logging any errors to excel. The code below seems to be working, but there is just the issue that the last of the 5 errors I see on the console log does not appear in the outputted CSV.
I have tried a range of alternatives including putting the csvWriter call in a .then rather than the .finally. The issue is that it is not waiting for the last error to be pushed to the array.
"use strict";
const okta = require("@okta/okta-sdk-nodejs");
const csv = require("csv-parser");
const fs = require("fs");
const createCsvWriter = require("csv-writer").createObjectCsvWriter;
let timeRun = new Date()
.toISOString()
.replace(/T/, " ") // replace T with a space
.replace(/\..+/, "") // delete the dot and everything after
.replace(/:/g, "."); // replace T with a space
const csvWriter = createCsvWriter({
path: "errorLog-" + timeRun + ".csv",
header: [
{ id: "error", title: "Error" },
{ id: "row", title: "Row" },
],
});
let record = [];
let currentError = {}
// Enter tenant info and API key here
const client = new okta.Client({
orgUrl: "https://xxxxxxxx.oktapreview.com",
token: "xxxxxxxxxxxxxxxxxxxxxxx",
});
let usersToDelete = [];
let currentUserID;
var getUsersToDelete = new Promise((resolve, reject) => {
fs.createReadStream("testImport.csv")
.pipe(csv())
.on("data", (row) => {
usersToDelete.push(row);
})
.on("end", (row) => {
resolve();
});
});
getUsersToDelete
.then(async () => {
let iCount = 1;
while (usersToDelete.length > 0) {
var deleteUserTimeout = new Promise((resolve, reject) => {
setTimeout(async function () {
currentUserID = usersToDelete.pop();
client
.getUser(currentUserID.email)
.then(async (user) => {
return user
.deactivate()
.then(() => console.log("User has been deactivated"))
.then(() => user.delete())
.then(() => console.log("User has been deleted"));
})
.catch(async function (error, row) {
currentError = { error: error.message, row: "row" };
console.error(currentError);
return error;
})
.finally(() => {
record.push(currentError);
reject()
});
resolve();
}, 2000);
});
await deleteUserTimeout;
console.log("Timeout" + currentUserID, "Iteration: " + iCount);
iCount++
}
}).finally(async () => {
await csvWriter.writeRecords(record);
});