// Dependencies declaration & setup // fs is for working with files, aka the JSON file we want to use to store our labels data const fs = require('fs'); // express is for setting up the server and make it works when users do their things in the browser const express = require('express'); const app = express(); const path = require('path'); // the port is setted in the etc/nginx/sites-enabled under the location /collecting-labels const port = 3124; // express middleware for working with JSON between the server (this) and the client (all the things in the public folder) app.use(express.urlencoded({ extended: true })); app.use(express.json()); // serves the contents of the public folder as static resources // i.e. then you can access it using https://hub.xpub.nl/soupboat/collecting-labels as root app.use('/collecting-labels', express.static('public')) // we dont need this now because express automatically uses the index.html file in the /public folder // (still need to understand how to get a notification when someone connects, but maybe it is just a callbac to the app.use function of line 19whe // app.get('/collecting-labels', function(req, res) { // res.sendFile(path.join(__dirname, 'public', 'index.html')); // console.log('Someone connected!') // }); // when a post request is made to the https://hub.xpub.nl/soupboat/collecting-labels url this function starts app.post('/collecting-labels', function(req, res) { // with fs we read the file labels.json inside the public folder // it is there because we then use the same file in the client for drawing all the labels stored in the server // don't know if it is a good idea or not tho // for now oke // also: we need to check that the contents of the post request is what we want aka a label object, structured as we want ecc // and not some other random thing, otherwise everything will break fs.readFile('public/labels.json', function(err, data) { if (err) throw err; // parse a JSON out of the labels.json file let storage = JSON.parse(data) // insert the req.body (aka our label object) to the labels array present inside the labels.json file storage.labels.push(req.body) // overwrite the labels.json file with all the data // this will not be efficient in the long term, but then we may switch to a proper database and not this scissor and glue thing fs.writeFile('public/labels.json', JSON.stringify(storage), (err)=>{ if (err) throw err; console.log('Data written to file');}) }) // reply to the client // TODO: sayng oke everything worked nice // for now it just echoes the incoming data res.send(req.body) }); // listen to the port we defined at the beginning aka wait for clients to connect there app.listen(port, function() { console.log(`🧶 → Collecting Labels on port ${port}!`) });