forked from nightscout/cgm-remote-monitor
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
172 lines (148 loc) · 5.77 KB
/
index.js
File metadata and controls
172 lines (148 loc) · 5.77 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
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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
'use strict';
var consts = require('../../constants');
function configure (app, wares, ctx) {
var express = require('express'),
api = express.Router( );
// invoke common middleware
api.use(wares.sendJSONStatus);
// text body types get handled as raw buffer stream
api.use(wares.rawParser);
// json body types get handled as parsed json
api.use(wares.jsonParser);
// also support url-encoded content-type
api.use(wares.urlencodedParser);
// Add format extension support
api.use(wares.extensions(['json', 'csv', 'txt', 'tsv']));
api.use(ctx.authorization.isPermitted('api:profile:read'));
/**
* @function formatWithSeparator
* Format profile data as CSV/TSV
*/
function formatWithSeparator(data, separator) {
if (data === null || data.constructor !== Array || data.length == 0) return "";
// Flatten the profile data for CSV export
var outputdata = [];
data.forEach(function(p) {
var profile = {
"_id": p._id || '',
"defaultProfile": p.defaultProfile || '',
"created_at": p.created_at || '',
"startDate": p.startDate || '',
"mills": p.mills || '',
"units": p.units || '',
"dia": p.dia || '',
"timezone": p.timezone || ''
};
outputdata.push(profile);
});
if (outputdata.length === 0) return "";
var fields = Object.keys(outputdata[0]);
var replacer = function(key, value) {
return value === null ? '' : value;
};
// Create header row
var csv = [fields.join(separator)];
// Add data rows
csv = csv.concat(outputdata.map(function(row) {
return fields.map(function(fieldName) {
return JSON.stringify(row[fieldName], replacer);
}).join(separator);
}));
return csv.join('\r\n');
}
/**
* @function query_models
* Perform the standard query logic, translating API parameters into mongo
* db queries in a fairly regimented manner.
* This middleware executes the query, returning the results as JSON/CSV
*/
function query_models (req, res, next) {
var query = req.query;
// If "?count=" is present, use that number to decide how many to return.
if (!query.count) {
query.count = consts.PROFILES_DEFAULT_COUNT;
}
// perform the query
ctx.profile.list_query(query, function payload(err, profiles) {
if (err) {
return res.sendJSONStatus(res, consts.HTTP_INTERNAL_ERROR, 'Mongo Error', err);
}
return res.format({
'text/plain': function() {
var output = formatWithSeparator(profiles, "\t");
res.send(output);
},
'text/tab-separated-values': function() {
var output = formatWithSeparator(profiles, '\t');
res.send(output);
},
'text/csv': function() {
var output = formatWithSeparator(profiles, ',');
res.send(output);
},
'application/json': function() {
res.json(profiles);
},
'default': function() {
res.json(profiles);
}
});
});
}
// List profiles available
api.get('/profiles/', query_models);
// List profiles available
api.get('/profile/', function(req, res) {
const limit = req.query && req.query.count ? Number(req.query.count) : consts.PROFILES_DEFAULT_COUNT;
ctx.profile.list(function (err, attribute) {
return res.json(attribute);
}, limit);
});
// List current active record (in current state LAST record is current active)
api.get('/profile/current', function(req, res) {
ctx.profile.last( function(err, records) {
return res.json(records.length > 0 ? records[0] : null);
});
});
function config_authed (app, api, wares, ctx) {
// create new record
api.post('/profile/', ctx.authorization.isPermitted('api:profile:create'), function(req, res) {
var data = req.body;
ctx.purifier.purifyObject(data);
ctx.profile.create(data, function (err, created) {
if (err) {
res.sendJSONStatus(res, consts.HTTP_INTERNAL_ERROR, 'Mongo Error', err);
console.log('Error creating profile');
console.log(err);
} else {
res.json(created.ops);
console.log('Profile created', created);
}
});
});
// update record
api.put('/profile/', ctx.authorization.isPermitted('api:profile:update'), function(req, res) {
var data = req.body;
ctx.profile.save(data, function (err, created) {
if (err) {
res.sendJSONStatus(res, consts.HTTP_INTERNAL_ERROR, 'Mongo Error', err);
console.log('Error saving profile');
console.log(err);
} else {
res.json(created);
console.log('Profile saved', created);
}
});
});
api.delete('/profile/:_id', ctx.authorization.isPermitted('api:profile:delete'), function(req, res) {
ctx.profile.remove(req.params._id, function ( ) {
res.json({ });
});
});
}
if (app.enabled('api')) {
config_authed(app, api, wares, ctx);
}
return api;
}
module.exports = configure;