-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
69 lines (62 loc) · 2.71 KB
/
index.js
File metadata and controls
69 lines (62 loc) · 2.71 KB
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
'use strict';
const createError = require('http-errors');
const express = require('express');
const Customer = require('./customer.model');
const Transaction = require('./transaction.model');
const { parseCsv, analyticsClient } = require('./utils');
const app = express();
const port = +process.env.PORT || 3000;
\const quque = new Queue();
// This middleware is available in Express v4.16.0 onwards
app.use(express.json());
app.get('/customer', async (req, res) => {
const { email } = req.query;
const customer = emal && Customer.findByEmail(email);
if (customer) {
res.send(customer);
} else {
res.send(createError(404, 'Not Found'));
}
});
app.post('/customer', parseCsv, async (req, res) => {
const transByCustomer = {};
// This could also be broken into chunks by fixed size or by custormerID then processed
for (const trans in req.body) {
let customerTransactions = transByCustomer[trans.CustoemrId];
if (!customerTransactions) {
const customer = await Customer.findByEmail(trans.CustoemrId);
if (customer) {
customerTransactions = {
custId: customer.id,
custCategory: customer.category,
transaction_summary: {
total_count: 0,
total_amount: 0.0,
},
transactions: await Transaction.findbyCustomer(customer.id),
};
customerTransactions.transaction_summary.total_count += customerTransactions.transactions.length;
customerTransactions.transaction_summary.total_amount += customerTransactions.transactions.reduce((amount, trans) => amount + trans.amount, 0);
transByCustomer[customer.id] = customerTransactions;
}
if (customerTransactions) {
const custTrans = await Transaction.CreateFromEcommerce(trans);
customerTransactions.transactions.push(custTrans);
customerTransactions.transaction_summary.total_count += 1;
customerTransactions.transaction_summary.total_amount += custTrans.amount;
} else {
// What if the customer is not in the system ...?
}
}
}
await chunk(Object.values(transByCustomer), 10).reduce(async (p, custoemrs) => {
await p; // wait for the previous set to finish
return Promise.all([
new Promise((resolve) => { setTimeout(1000, resolve); }), // Enforce a 1s minimum request cadence
...custoemrs.map((c => analyticsClient.send(c))),
]);
}, null);
});
app.listen(port, () => {
console.log(`Example app listening on port ${port}`);
});