Skip to content

Commit 41145af

Browse files
sulkaharomrspouse
authored andcommitted
Support uploading device statuses in batches (nightscout#6147)
* Support uploading device statuses in batches * Correctly report batch insertion results
1 parent 3fb4158 commit 41145af

File tree

1 file changed

+45
-25
lines changed

1 file changed

+45
-25
lines changed

lib/server/devicestatus.js

Lines changed: 45 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -5,34 +5,51 @@ var find_options = require('./query');
55

66
function storage (collection, ctx) {
77

8-
function create (obj, fn) {
9-
10-
// Normalize all dates to UTC
11-
const d = moment(obj.created_at).isValid() ? moment.parseZone(obj.created_at) : moment();
12-
obj.created_at = d.toISOString();
13-
obj.utcOffset = d.utcOffset();
14-
15-
api().insertOne(obj, function(err, results) {
16-
if (err !== null && err.message) {
17-
console.log('Error inserting the device status object', err.message);
18-
fn(err.message, null);
19-
return;
20-
}
8+
function create (statuses, fn) {
219

22-
if (!err) {
10+
if (!Array.isArray(statuses)) { statuses = [statuses]; }
2311

24-
if (!obj._id) obj._id = results.insertedIds[0]._id;
12+
const r = [];
13+
let errorOccurred = false;
2514

26-
ctx.bus.emit('data-update', {
27-
type: 'devicestatus'
28-
, op: 'update'
29-
, changes: ctx.ddata.processRawDataForRuntime([obj])
30-
});
31-
}
15+
for (let i = 0; i < statuses.length; i++) {
3216

33-
fn(null, results.ops);
34-
ctx.bus.emit('data-received');
35-
});
17+
const obj = statuses[i];
18+
19+
if (errorOccurred) return;
20+
21+
// Normalize all dates to UTC
22+
const d = moment(obj.created_at).isValid() ? moment.parseZone(obj.created_at) : moment();
23+
obj.created_at = d.toISOString();
24+
obj.utcOffset = d.utcOffset();
25+
26+
api().insertOne(obj, function(err, results) {
27+
if (err !== null && err.message) {
28+
console.log('Error inserting the device status object', err.message);
29+
errorOccurred = true;
30+
fn(err.message, null);
31+
return;
32+
}
33+
34+
if (!err) {
35+
36+
if (!obj._id) obj._id = results.insertedIds[0]._id;
37+
r.push(obj);
38+
39+
ctx.bus.emit('data-update', {
40+
type: 'devicestatus'
41+
, op: 'update'
42+
, changes: ctx.ddata.processRawDataForRuntime([obj])
43+
});
44+
45+
// Last object! Return results
46+
if (i == statuses.length - 1) {
47+
fn(null, r);
48+
ctx.bus.emit('data-received');
49+
}
50+
}
51+
});
52+
};
3653
}
3754

3855
function last (fn) {
@@ -109,7 +126,10 @@ function storage (collection, ctx) {
109126
api.aggregate = require('./aggregate')({}, api);
110127
api.indexedFields = [
111128
'created_at'
112-
129+
130+
131+
132+
113133
, 'NSCLIENT_ID'
114134
];
115135
return api;

0 commit comments

Comments
 (0)