API_Server_and_Client_Example/apiserver_with_sqlite.js

154 lines
4.5 KiB
JavaScript

const express = require('express')
const bodyParser = require('body-parser')
const app = express()
const sqlite3 = require('sqlite3').verbose()
const port = 5000
const db = new sqlite3.Database('counters.db')
const make_table = "CREATE TABLE IF NOT EXISTS counters \
(counter_name TEXT PRIMARY KEY, counter_value INTEGER)"
const add_counter = "INSERT INTO counters VALUES (?, ?)"
const get_all_counters = "SELECT * FROM counters"
const increment_counter = "UPDATE counters \
SET counter_value = (SELECT counter_value FROM counters WHERE counter_name = ?) + 1 \
WHERE counter_name = ?"
const decrement_counter = "UPDATE counters \
SET counter_value = (SELECT counter_value FROM counters WHERE counter_name = ?) - 1\
WHERE counter_name = ?"
db.run(make_table)
app.use(bodyParser.json())
function rows_to_dict(rows) {
dictionary = {}
rows.forEach((row) => {
dictionary[row["counter_name"]] = row["counter_value"]
})
return dictionary
}
app.get("/counters", (req, res) => {
db.all(get_all_counters, (err, rows) => {
res.status(200).send({
'all_counters': rows_to_dict(rows)
})
})
})
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
}
db.run(add_counter, 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) => {
db.all(get_all_counters, (err, rows) => {
counters = rows_to_dict(rows)
if (!req.params.counterName in Object.keys(counters)) {
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': counters[req.params.counterName]
}
res.status(200).send(data_response)
})
})
app.post("/counters/:counterName/increment", (req, res) => {
db.all(get_all_counters, (err, rows) => {
counters = rows_to_dict(rows)
if (!req.params.counterName in Object.keys(counters)) {
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': counters[req.params.counterName],
'new_value': counters[req.params.counterName] + 1
}
db.run(increment_counter, req.params.counterName, req.params.counterName)
res.status(200).send(data_response)
})
})
app.post("/counters/:counterName/decrement", (req, res) => {
db.all(get_all_counters, (err, rows) => {
counters = rows_to_dict(rows)
if (!req.params.counterName in Object.keys(counters)) {
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': counters[req.params.counterName],
'new_value': counters[req.params.counterName] - 1
}
db.run(decrement_counter, req.params.counterName, req.params.counterName)
res.status(200).send(data_response)
})
})
app.listen(port, () => {
console.log(`Server is running on port ${port}`)
})
app.on("exit", () => {
db.close()
})