我的项目的几个文件中有这段代码,我知道重复代码是不好的做法。所以我决定在不同的文件中编写一个函数来返回所需的结果,但它不起作用。这似乎是弹性搜索代码的特殊之处。这是我最初在 course.js 中工作正常的内容:
...
const { body: bulkResponse } = await client.bulk({ refresh: true, body });
if (bulkResponse.errors) {
const erroredDocuments = [];
bulkResponse.items.forEach((action, i) => {
const operation = Object.keys(action)[0];
if (action[operation].error) {
erroredDocuments.push({
status: action[operation].status,
error: action[operation].error,
operation: body[i * 2],
document: body[i * 2 + 1]
});
}
});
console.log(erroredDocuments);
...
然后我将 course.js 中的代码段替换为:
const {checkIfIndexExists, bulkIndexing } = require('../../utils/util')
...
bulkIndexing(body);
...
//in util.js i have this
/**
* @description this function performs bulk index of model once the input array is prepared for indexing
* @param {Array} indexBulkArray Array of index and the respective object to be indexed
* @returns null
*/
const bulkIndexing = async (indexBulkArray)=>{
try {
const { body: bulkResponse } = await client.bulk({ refresh: true, body: indexBulkArray });
if (bulkResponse.errors) {
const erroredDocuments = [];
bulkResponse.items.forEach((action, i) => {
const operation = Object.keys(action)[0];
if (action[operation].error) {
erroredDocuments.push({
status: action[operation].status,
error: action[operation].error,
operation: body[i * 2],
document: body[i * 2 + 1]
});
}
});
console.log(erroredDocuments);
}
} catch (error) {
console.log(error)
}
}
module.exports = {
...
bulkIndexing,
...
};
我收到错误
TypeError: bulkIndexing is not a function