我正在尝试从 Okta 导入和删除大量用户,同时保持在速率限制内,并将任何错误记录到 Excel 中。下面的代码似乎可以正常工作,但只是我在控制台日志中看到的 5 个错误中的最后一个没有出现在输出的 CSV 中。
我尝试了一系列替代方法,包括将 csvWriter 调用放在 .then 而不是 .finally 中。问题是它没有等待最后一个错误被推送到数组。
"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);
});