const express = require('express') const bodyParser = require('body-parser') const app = express() const port = 5000 let data_store = {} app.use(bodyParser.json()) app.get("/counters", (req, res) => { res.status(200).send({ 'all_counters': data_store }) }) app.post("/counters", (req, res) => { if (req.headers['content-type'] == 'application/json') { body = req.body; if (!"new_counter_name" in Object.keys(body) || !"new_counter_starting_value" in Object.keys(body)) { error_response = { "status": "ERROR", "reason": "Body for posting to /counters endpoint must contain both new_counter_name and new_counter_starting_value", "input_body": body } res.status(400).send(error_response) return } data_store[body["new_counter_name"]] = body["new_counter_starting_value"] res.status(200).send({'status': 'OK'}) } else { error_response = { "status": "ERROR", "reason": "Content Type for endpoint /counters must be application/json" } res.status(400).send(error_response) } }) app.get("/counters/:counterName", (req, res) => { if (!req.params.counterName in Object.keys(data_store)) { error_response = { "status": "ERROR", "reason": `Counter name ${req.params.counterName} does not exist` } res.status(404).send(error_response) return } data_response = { 'counter_name': req.params.counterName, 'counter_value': data_store[req.params.counterName] } res.status(200).send(data_response) }) app.post("/counters/:counterName/increment", (req, res) => { if (!req.params.counterName in Object.keys(data_store)) { error_response = { "status": "ERROR", "reason": `Counter name ${req.params.counterName} does not exist` } res.status(404).send(error_response) return } data_response = { 'counter_name': req.params.counterName, 'old_value': data_store[req.params.counterName], 'new_value': data_store[req.params.counterName] + 1 } data_store[req.params.counterName] = data_store[req.params.counterName] + 1 res.status(200).send(data_response) }) app.post("/counters/:counterName/decrement", (req, res) => { if (!req.params.counterName in Object.keys(data_store)) { error_response = { "status": "ERROR", "reason": `Counter name ${req.params.counterName} does not exist` } res.status(404).send(error_response) return } data_response = { 'counter_name': req.params.counterName, 'old_value': data_store[req.params.counterName], 'new_value': data_store[req.params.counterName] - 1 } data_store[req.params.counterName] = data_store[req.params.counterName] - 1 res.status(200).send(data_response) }) app.listen(port, () => { console.log(`Server is running on port ${port}`) })