103 lines
2.4 KiB
JavaScript
103 lines
2.4 KiB
JavaScript
const express = require('express');
|
|
const fs = require('fs');
|
|
const sqlite3 = require('sqlite3').verbose();
|
|
const router = express.Router();
|
|
|
|
let weight_db;
|
|
const file = `${process.env.DB_HOME}/` + 'weight.db';
|
|
|
|
/* GET users listing. */
|
|
|
|
function createWeightDB() {
|
|
console.log('Creating Weight db...');
|
|
|
|
console.log(file);
|
|
if (!fs.existsSync(file)) {
|
|
console.log('creating db file');
|
|
fs.openSync(file, 'w');
|
|
|
|
weight_db = new sqlite3.Database(file, createWeightTable);
|
|
|
|
weight_db.close();
|
|
}
|
|
}
|
|
|
|
function connectWeightDB() {
|
|
'use strict';
|
|
console.log('Connect db.');
|
|
weight_db = new sqlite3.Database(file);
|
|
}
|
|
|
|
function createWeightTable() {
|
|
console.log('Creating weight table...');
|
|
weight_db.run('CREATE TABLE IF NOT EXISTS weight (date text, reading real);');
|
|
}
|
|
|
|
function closeWeightDB() {
|
|
'use strict';
|
|
console.log('Closing db.');
|
|
weight_db.close();
|
|
}
|
|
|
|
function insertWeightReading(time, reading) {
|
|
console.log(`Inserting reading:${ reading}`);
|
|
|
|
// var sql = db.prepare('INSERT into temperature(date, reading) VALUES
|
|
// (?,?)',[time],[reading]);
|
|
|
|
weight_db.run('BEGIN TRANSACTION');
|
|
weight_db.run('INSERT into weight(date, reading) VALUES (?,?)', [time, reading]);
|
|
|
|
weight_db.run('END');
|
|
}
|
|
|
|
router.get('/', function(req, res, next) {
|
|
const now = new Date();
|
|
|
|
const t = req.query;
|
|
|
|
if (req.query != {} && req.query.weight != null) {
|
|
// createDB();
|
|
console.log(req.query);
|
|
connectWeightDB();
|
|
|
|
insertWeightReading(now.toJSON(), parseFloat(req.query.weight) );
|
|
|
|
closeWeightDB();
|
|
|
|
res.writeHead(200, { 'ContentType': 'application/json' });
|
|
// res.send(JSON.stringify(t));
|
|
res.end(JSON.stringify(t));
|
|
}
|
|
else
|
|
res.render('weight', { });
|
|
});
|
|
|
|
router.get('/all', function(req, res, next) {
|
|
'use strict';
|
|
console.log('Selecint all..');
|
|
connectWeightDB();
|
|
|
|
weight_db.all('SELECT * from weight', function(err, rows) {
|
|
const out = [];
|
|
console.log(err);
|
|
console.log(rows);
|
|
rows.forEach(function (row) {
|
|
console.log(`${row.date }, ${ row.reading}`);
|
|
// var t = ;
|
|
// out.push({"date": Date(row.date), "reading":row.reading});
|
|
out.push({ 'date': row.date, 'reading':row.reading });
|
|
});
|
|
|
|
res.writeHead(200, { 'ContentType': 'application/json' });
|
|
// res.send(JSON.stringify(t));
|
|
res.end(JSON.stringify(out));
|
|
|
|
closeWeightDB();
|
|
});
|
|
});
|
|
|
|
module.exports = router;
|
|
|
|
createWeightDB();
|