【发布时间】:2021-05-11 22:33:59
【问题描述】:
我目前正在编写一个财务跟踪应用程序,并从 CSV 文件构建了一个数据导入,用于检查数据库中是否已经存在条目,如果没有,则将某个类别添加到条目中,然后将其保存到数据库中。
导入 CSV 文件后,我想输出作为对发布请求的响应:导入条目的数量以及未找到合适类别的所有条目。不幸的是,由于 Nestjs 的异步方法,我失败了。但是,我的响应是在其他功能完成之前输出的。这样第一个导入总是“imports: 0”和“unsortedTransactions: []。 ”
如何在控制器中等待所有功能完成后再返回响应? 事务控制器:
@Controller('transactions')
export class TransactionController {
constructor(
private transactionService: TransactionService,
private labelService: LabelService,
) {}
@Post()
@UseInterceptors(
FileInterceptor('file', {
storage: diskStorage({
destination: './uploads/csv',
filename: randomFilename,
}),
}),
)
public createTransactions(
@Response() response,
@UploadedFile() file,
@Request() request,
) {
let imports = 0;
fs.createReadStream(path.resolve(file.path), {
encoding: 'utf-8',
})
.pipe(csv.parse({ headers: false, delimiter: ';', skipRows: 1 }))
.on('data', (data) => {
const timestamp = new Date()
.toISOString()
.slice(0, 19)
.replace('T', ' ');
const amount = parseFloat(data[14].replace(',', '.'));
const bankaccountId = request.body.bankaccount_id;
const bookingDate = this.createDate(data[1]);
const name = data[11].replace(/\s\s+/g, ' ');
const usage = data[4].replace(/\s\s+/g, ' ');
this.transactionService
.checkDuplicate(amount, name, usage, bookingDate)
.then((entry) => {
if (entry.length === 0) {
this.sortLabel(data).then((label_id) => {
const newTransaction = {
amount,
name,
usage,
label_id,
bankaccount_id: bankaccountId,
booking_date: bookingDate,
created_at: timestamp,
updated_at: timestamp,
};
this.transactionService.create(newTransaction);
imports++;
});
}
});
});
const unsortedTransactions = this.transactionService.getUnsorted();
return response.send({ unsortedTransactions, imports });
}
private async sortLabel(transaction: Transaction): Promise<any> {
let label_id = 1;
const labels = await this.labelService.getAll();
const name = transaction[11].replace(/\s\s+/g, ' ').toLowerCase();
const usage = transaction[4].replace(/\s\s+/g, ' ').toLowerCase();
labels.forEach((label) => {
if (label.keywords != null) {
const keywords = label.keywords.split(',');
keywords.forEach((keyword) => {
if (
name.includes(keyword.toLowerCase()) ||
usage.includes(keyword.toLowerCase())
) {
label_id = label.id;
}
});
}
});
return await label_id;
}
private createDate(date: string): string {
const dateArray = date.split('.');
return `20${dateArray[2]}-${dateArray[1]}-${dateArray[0]}`;
}
}
交易服务:
export class TransactionService {
constructor(
@InjectRepository(Transaction)
private readonly transactionRepository: Repository<Transaction>,
) {}
public create(transaction): Promise<Transaction> {
return this.transactionRepository.save(transaction);
}
public getAll(): Promise<Transaction[]> {
return this.transactionRepository.find({
relations: ['label_id', 'bankaccount_id'],
});
}
public getUnsorted(): Promise<Transaction[]> {
return this.transactionRepository.find({
where: {
label_id: 1,
},
});
}
public checkDuplicate(
amount: number,
name: string,
usage: string,
booking_date: string,
): Promise<Transaction[]> {
return this.transactionRepository.find({
where: {
amount,
name,
usage,
booking_date,
},
});
}
}
【问题讨论】:
-
太复杂了,你用的是哪个数据库?如果条目存在,findOne 可以检查(续集)。
-
我使用的是 mySQL 数据库
标签: javascript typescript async-await promise nestjs