return new and existing real estates when saving results

This commit is contained in:
Bilal Catic
2019-09-25 08:32:37 +02:00
parent f93d0e738f
commit b3fcc6ba9a
2 changed files with 26 additions and 47 deletions

View File

@@ -1,9 +1,6 @@
const moment = require("moment");
const {
bulkUpsertRealEstates,
checkIfAlreadyExist
} = require("../../helpers/db/realEstate");
const { bulkUpsertRealEstates } = require("../../helpers/db/realEstate");
class PostgresSaver {
connect() {
@@ -14,27 +11,33 @@ class PostgresSaver {
async save(results) {
console.log("[POSTGRES] Saving...");
const resultsWithPublishedAndRenewedDateSame = results.filter(
realEstate => {
const { publishedDate, renewedDate } = realEstate;
const publishedMomentDate = moment.utc(publishedDate);
const renewedMomentDate = moment.utc(renewedDate);
return publishedMomentDate.isSame(renewedMomentDate, "minute");
}
);
const exist =
resultsWithPublishedAndRenewedDateSame.length > 0
? await checkIfAlreadyExist(resultsWithPublishedAndRenewedDateSame)
: false;
const savedRecords = await bulkUpsertRealEstates(results);
return {
exist,
savedRecords
};
if (Array.isArray(savedRecords)) {
const newRealEstates = [];
const existingRealEstates = [];
for (const savedRecord of savedRecords) {
const { createdAt, updatedAt } = savedRecord;
const createdAtMoment = moment.utc(createdAt);
const updatedAtMoment = moment.utc(updatedAt);
if (createdAtMoment.isSame(updatedAtMoment, "second")) {
newRealEstates.push(savedRecord);
} else {
existingRealEstates.push(savedRecord);
}
}
return {
newRecords: newRealEstates,
existingRecords: existingRealEstates
};
} else {
throw { message: "[POSTGRES] Failed to save records" };
}
}
close() {