// This program uses Node.js and Express.js to create a simple REST API.
//
// References:
// https://medium.com/@onejohi/building-a-simple-rest-api-with-nodejs-and-express-da6273ed7ca9
"use strict";
const express = require("express");
const server = express();
const cors = require('cors')
server.use(cors());
const bodyParser = require('body-parser');
server.use(bodyParser.json());
let records = [];
let lastID = 0;
server.get("/", (request, response, next) => {
const path = require('path');
let filename = path.join(__dirname, "index.html");
response.sendFile(filename);
});
server.get("/records", (request, response, next) => {
response.send(JSON.stringify(records, null, 2));
});
server.get("/records/:id", (request, response, next) => {
let index = records.findIndex(record => record.id == request.params.id);
if (index == -1) {
response.status(404);
response.send("Not found");
}
else {
response.send(JSON.stringify(records[index], null, 2));
}
});
server.post("/records", (request, response, next) => {
let record = request.body;
record["id"] = ++lastID;
records.push(record);
response.status(201);
response.send(JSON.stringify(record, null, 2));
});
server.put("/records/:id", (request, response, next) => {
let index = records.findIndex(record => record.id == request.params.id);
if (index == -1) {
response.status(404);
response.send("Not found");
} else {
let record = request.body;
record["id"] = request.params.id;
records[index] = record;
response.send(JSON.stringify(record, null, 2));
}
});
server.delete("/records/:id", (request, response, next) => {
let index = records.findIndex(record => record.id == request.params.id);
if (index == -1) {
response.status(404);
response.send("Not found");
} else {
let record = records.splice(index, 1);
response.send(JSON.stringify(record, null, 2));
}
});
server.listen(3000, () => {
console.log("Server running on port 3000");
});