【发布时间】:2021-03-21 09:30:58
【问题描述】:
郑重声明,我是一个相对较新的程序员
我的代码可以运行,但是如果要对许多项目进行排序,它会显得笨重且缓慢
当然,这个节点应用程序不需要很快,即该过程可能需要 5 分钟,这会很好,但我很好奇是否有更好的方法来做到这一点......
我有这个节点应用程序,它正在比较两个数据集...程序的目标如下
- 将 csv 文件与在线 api 进行比较
- 确保 csv 文件中的所有名称都存在于数组中
- 向屏幕抛出错误 (console.log()) 消息而不是完成
现在是代码
const fs = require("fs");
const csv = require("csv-parser");
const fetch = require("node-fetch");
const results = [];
fs.createReadStream("./customers.csv")
.pipe(csv())
.on("data", (data) => {
results.push(data);
})
.on("end", () => {
console.log("Getting Customer Data from Waze...");
fetch("https://gql.waveapps.com/graphql/public", {
method: "post",
headers: {
//prettier-ignore
'Authorization': "Bearer MyAuth",
"Content-Type": "application/json",
},
body: JSON.stringify({
query: `
query {
business(id: "MyBusinessId") {
customers {
edges {
node {
id
name
}
}
}
}
}
`,
}),
})
.then((res) => res.json())
.then(({ data }) => {
console.log("Filtering Data...");
// this maps through the csv file
results.map((csv) => {
let array = [];
name = "";
data.business.customers.edges.map((customer) => {
// push the results of the expression (true of false) to an array
array.push(
customer.node.name.toLowerCase() === csv.name.toLowerCase()
);
// push nonexistent name (if there is one) variable so error handling is clear
if (customer.node.name.toLowerCase() !== csv.name.toLowerCase()) {
name = csv.name;
}
});
// if all elements in array are false, that means there is no matching name in the data.business.customers.edges array and error will be true, if there is a true field in the name, return false
const error = !array.some((el) => {
if (el) {
return true;
}
});
if (error) {
return console.log(
`Name: ${name} not found in Waze customer list, please check your spelling`
);
}
// send http request here
});
console.log("Finished Sending Invoices");
});
});
customer.csv 文件
"name","domain","expiration-date"
"bob","yahoo.com","7/2/2020"
"suzie","google.com","12/1/2020"
现在,graphql api 返回的数据看起来像这样......
[
{
node: {
id: 'QnVzaW5lc3M6MzE4NmRmNDQtZDg4Zi00MzgxLTk5ZGEtYTQzMWRmYzhmMDk5O0N1c3RvbWVyOjQ3NTg0Mzc2',
name: 'NOInvoice'
}
},
{
node: {
id: 'QnVzaW5lc3M6MzE4NmRmNDQtZDg4Zi00MzgxLTk5ZGEtYTQzMWRmYzhmMDk5O0N1c3RvbWVyOjQ3NTg0MzU3',
name: 'Suzie'
}
},
{
node: {
id: 'QnVzaW5lc3M6MzE4NmRmNDQtZDg4Zi00MzgxLTk5ZGEtYTQzMWRmYzhmMDk5O0N1c3RvbWVyOjQ3NTgwODkx',
name: 'Bob'
}
}
]
任何帮助将不胜感激
【问题讨论】:
-
好吧,如果您需要不匹配的属性名称,我看不出有什么办法。您可以 JSON.stringify 两个数组并将它们的结果作为初始检查进行比较,以查看是否需要进一步检查。
标签: javascript node.js arrays filtering