Files
cgm-remote-monitor/lib/server/devicestatus.js
T
Sulka HaroandGitHub b04476e1f9 Normalize Treatment, Entry and Device Status object dates to be all in UTC Strings (#4658)
* Normalize Treatment object dates to be all in UTC Strings, as expected by the codebase

* Also normalize the device status data

* Sort the results so results with mixed dates are returned in correct order

* Use MomentJS to correctly parse the offsets & output the offset to objects at all times

* Removing a debug console log message causing excessive logging

* Use UTC date values for queries even if client asks for zoned dates

* Remove extra sorting based on date. Code clarifications

* * Add missing parseZone() call to treatments
* Check isValid() date on entries

* Use isValid() to check date validity for device status data
2019-07-17 09:03:39 +03:00

97 lines
2.2 KiB
JavaScript

'use strict';
var moment = require('moment');
var find_options = require('./query');
function storage (collection, ctx) {
var ObjectID = require('mongodb').ObjectID;
function create(obj, fn) {
// Normalize all dates to UTC
const d = moment(obj.created_at).isValid() ? moment.parseZone(obj.created_at) : moment();
obj.created_at = d.toISOString();
obj.utcOffset = d.utcOffset();
api().insert(obj, function (err, doc) {
if (err != null && err.message) {
console.log('Error inserting the device status object', err.message);
fn(err.message, null);
return;
}
fn(null, doc.ops);
ctx.bus.emit('data-received');
});
}
function last(fn) {
return list({count: 1}, function (err, entries) {
if (entries && entries.length > 0) {
fn(err, entries[0]);
} else {
fn(err, null);
}
});
}
function query_for (opts) {
return find_options(opts, storage.queryOpts);
}
function list(opts, fn) {
// these functions, find, sort, and limit, are used to
// dynamically configure the request, based on the options we've
// been given
// determine sort options
function sort ( ) {
return opts && opts.sort || {created_at: -1};
}
// configure the limit portion of the current query
function limit ( ) {
if (opts && opts.count) {
return this.limit(parseInt(opts.count));
}
return this;
}
// handle all the results
function toArray (err, entries) {
fn(err, entries);
}
// now just stitch them all together
limit.call(api( )
.find(query_for(opts))
.sort(sort( ))
).toArray(toArray);
}
function remove (opts, fn) {
return api( ).remove(query_for(opts), fn);
}
function api() {
return ctx.store.collection(collection);
}
api.list = list;
api.create = create;
api.query_for = query_for;
api.last = last;
api.remove = remove;
api.aggregate = require('./aggregate')({ }, api);
api.indexedFields = [
'created_at'
, 'NSCLIENT_ID'
];
return api;
}
storage.queryOpts = {
dateField: 'created_at'
};
module.exports = storage;