const express = require('express'); const compression = require('compression') const bodyParser = require('body-parser'); const low = require('lowdb'); const lodashId = require('lodash-id'); const FileAsync = require('lowdb/adapters/FileAsync'); const app = express(); // app is an instance of express app.use(compression()); // enables gzip compression app.use(bodyParser.urlencoded({ extended: false })) // parse application/x-www-form-urlencoded app.use(bodyParser.json()) // parse application/json app.use(express.static(__dirname + '/build')); // serve static build site app.get('/a', (req, res) => { res.send(process.env); }); // Create database instance and start server // const adapter = new FileAsync(__dirname + '/db.json'); low(new FileAsync(__dirname + '/db.json')) // production // low(new FileAsync('/tmp/db.json')) // dev .then(db => { db._.mixin(lodashId); // DATABASE ROUTES // ============== app.post('/test',(req,res)=>{ // "reason": { // "fitali": req.body.reason.toString() === "fvitali" ? 1:0, // "": req.body.reason.toString() === "" ? 1:0, // "": req.body.reason.toString() === "" ? 1:0, // } // try { // let test = table.updateById(req.body.id, { }) // } // catch(e) { // } res.send(req.body); }); // ============== // GET /videotrack/:id? app.get('/videotrack/:id?', (req, res) => { const videos = db.get('videos'); req.params.id ? res.send(videos.getById(req.params.id).value()) : res.send(videos.value()) }); // POST /videotrack app.post('/videotrack', (req, res) => { const videos = db.get('videos'); const row = videos.getById(req.body.id); if(row.value()) { row .update('timesWatched',(n) => ++n) .update('lastWatched',() => new Date().toISOString()) .write() .then(output => res.send(output)) } else { let newRow = { "id": req.body.id.toString(), "timesWatched": 1, "lastWatched": new Date().toISOString(), } videos.push(newRow).last().write().then(output => res.send(output)) } }); // Set db default values return db.defaults({ videos: [] }).write(); }) .then(() => { app.listen(8000, () => console.log('listen on 8000')); // bind to port 8000 as required from specs });