-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
128 lines (106 loc) · 3.61 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
require('dotenv').config({ path: './.env' });
const Hubspot = require('hubspot');
const hubspot = new Hubspot({ apiKey: process.env.HUBSPOT_API_KEY });
const Promise = require('bluebird');
const mongoose = require('mongoose');
const { scrape } = require('./src/scraper');
const Customer = require('./src/models/Customer.js');
const today = new Date();
async function init() {
console.log('Date: ' + today);
return new Promise(function(resolve, reject) {
// Set up default mongoose connection
mongoose.connect(process.env.DB_LOCATION, err => {
if (err) {
console.log(err);
process.exit(1);
}
});
// Get the default connection
let db = mongoose.connection;
db.on('connected', () => {
console.log('MongoDB connected');
resolve();
});
db.on('error', err => {
console.log('MongoDB error: ' + err);
reject(err);
});
});
}
async function run(options) {
try {
await init();
let data = await scrape(options);
console.log('Scraped ' + data.length + ' customers');
console.log('Checking database for customers...');
let promises = data.map(customer => {
return new Promise((resolve, reject) => {
Customer.findOne({
email: customer.email,
}).exec((err, res) => {
if (err) console.log(err);
if (!res) resolve(customer);
resolve(null);
});
});
});
data = await Promise.all(promises);
data = data.filter(obj => obj !== null);
console.log('Uploading ' + data.length + ' customers to HubSpot...');
promises = data.map(customer => {
return new Promise(async (resolve, reject) => {
hubspot.contacts
.createOrUpdate(customer.email, {
properties: [
{
property: 'firstname',
value: customer.firstname || '',
},
{
property: 'lastname',
value: customer.lastname || '',
},
{
property: 'branch',
value: customer.branch || '',
},
{
property: 'dealer_customer_portal',
value: 'yes',
},
],
})
.then(async res => {
console.log(res);
createCustomer(customer).then(() => {
resolve();
});
})
.catch(err => {
console.log(err);
resolve();
});
});
});
await Promise.all(promises);
} catch (err) {
console.log(err);
process.exit(1);
}
process.exit(0);
}
async function createCustomer(data) {
let newCustomer = new Customer(data);
// Save new customer
await newCustomer.save(err => {
if (err) console.log(err);
return;
});
// Report that new customer was saved
console.log('Customer added to database: ' + data.email);
return;
}
module.exports = {
run,
};