Skip to content

Desc #145

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 12 commits into
base: feature/documentation
Choose a base branch
from
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
node_modules/
.env
/api/config/
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -184,7 +184,7 @@ This project is part of the following Open Source programs:
- [Django Docs](https://docs.djangoproject.com/en/3.0/)
- [React Docs](https://reactjs.org/docs/getting-started.html)
- [Node.js Docs](https://nodejs.org/api/)
- [Node.js Docs](https://nodejs.org/api)
- [Git and GitHub](https://www.digitalocean.com/community/tutorials/how-to-use-git-a-reference-guide)
21 changes: 21 additions & 0 deletions api/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# Water Monitoring API

## Installation

`npm install`

## Setting up

- Create a config folder in api/
- Create dev.json or test.json file based on your usecase
- Add the following code to dev/test.json

`{"dbURI":"YOUR DATABASE URI"}`

## Running

`npm start`

## Testing

`npm test`
10 changes: 10 additions & 0 deletions api/models/Reading.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
const mongoose = require("mongoose");

const readingSchema = new mongoose.Schema({
value: {
required: true,
type: String
}
});

module.exports = mongoose.model("reading", readingSchema);
1,875 changes: 1,875 additions & 0 deletions api/package-lock.json

Large diffs are not rendered by default.

43 changes: 43 additions & 0 deletions api/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
{
"name": "water-monitoring-system-api",
"version": "1.0.0",
"description": "This is the backend of the web based water monitoring system",
"main": "server.js",
"scripts": {
"start": "export NODE_ENV=dev && node server.js",
"test": "export NODE_ENV=test && mocha --exit --timeout 10000"
},
"repository": {
"type": "git",
"url": "git+https://github.com/vinitshahdeo/Water-Monitoring-System.git"
},
"keywords": [
"api",
"nodejs"
],
"author": "YashMeh",
"license": "MIT",
"bugs": {
"url": "https://github.com/vinitshahdeo/Water-Monitoring-System/issues"
},
"homepage": "https://github.com/vinitshahdeo/Water-Monitoring-System#readme",
"dependencies": {
"body-parser": "^1.19.0",
"config": "^3.3.0",
"cors": "^2.8.5",
"express": "^4.17.1",
"helmet": "^3.21.3",
"mongoose": "^5.9.2",
"morgan": "^1.9.1",
"node-esapi": "0.0.1",
"sanitizer": "^0.1.3"
},
"engines": {
"node": "8.11.4"
},
"devDependencies": {
"chai": "^4.2.0",
"chai-http": "^4.3.0",
"mocha": "^7.1.0"
}
}
61 changes: 61 additions & 0 deletions api/routes/readingRoutes.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
const express = require("express");
const sanitizer = require("sanitizer");
const router = express.Router();
const Reading = require("../models/Reading");
//Add a new reading
router.post("/new", (req, res) => {
//Sanitize the input to prevent malicious data
const reading = { value: sanitizer.sanitize(req.body.value) };
Reading.create(reading)
.then(result => {
res.status(201).json({ mssg: "Created", data: result });
})
.catch(err => {
res.status(500).json({ mssg: "Internal Error" });
});
});
//Read all readings
router.get("/all", (req, res) => {
Reading.find({})
.then(result => {
res.status(200).json({ mssg: "Ok", data: result });
})
.catch(err => {
res.status(500).json({ mssg: "Internal Error" });
});
});
//Read particular reading
router.get("/:readId", (req, res) => {
const readId = sanitizer.sanitize(req.params.readId);
Reading.findById(readId)
.then(result => {
res.status(200).json({ mssg: "Ok", data: result });
})
.catch(err => {
res.status(500).json({ mssg: "Internal Error" });
});
});
//Update particular reading
router.put("/:readId", (req, res) => {
const readId = sanitizer.sanitize(req.params.readId);
const value = sanitizer.sanitize(req.body.value);
Reading.findByIdAndUpdate(readId, { $set: { value } }, { new: true })
.then(result => {
res.status(200).json({ mssg: "Ok", data: result });
})
.catch(err => {
res.status(500).json({ mssg: "Internal Error" });
});
});
//Delete particular reading
router.delete("/:readId", (req, res) => {
const readId = sanitizer.sanitize(req.params.readId);
Reading.findByIdAndDelete(readId)
.then(result => {
res.status(200).json({ mssg: "Ok", data: result });
})
.catch(err => {
res.status(500).json({ mssg: "Internal Error" });
});
});
module.exports = router;
57 changes: 57 additions & 0 deletions api/server.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
const express = require("express"),
mongoose = require("mongoose"),
bodyParser = require("body-parser"),
cors = require("cors"),
helmet = require("helmet"),
morgan = require("morgan"),
config = require("config"),
app = express(),
port = process.env.PORT || 8080;

//Use the database uri from the ./config directory
const dbURI = config.dbURI;
mongoose
.connect(dbURI, { useNewUrlParser: true, useUnifiedTopology: true })
.then(res => {
console.log("Database connected successfully.");
})
.catch(err => {
throw err;
});

//Configuring the express instance
// Prevent misconfig headers
app.disable("x-powered-by");

// Prevent opening page in frame or iframe to protect from clickjacking
app.use(helmet.frameguard());

// Prevents browser from caching and storing page
app.use(helmet.noCache());

// use bodyParser to parse application/json content-type
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

// enable all CORS requests
app.use(cors());

//If executing in test environment then prevent logging
if (config.util.getEnv("NODE_ENV") !== "test") {
// log HTTP requests
app.use(morgan("combined"));
}

//Requiring Routes
const readingRoutes = require("./routes/readingRoutes");

//Using Routes
app.use("/api/reading", readingRoutes);

//Starting the server
app.listen(port, err => {
if (err) throw err;
console.log(`Server running at port ${port}`);
});

module.exports = app; // for testing
42 changes: 42 additions & 0 deletions api/test/Reading.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
const Reading = require("../models/Reading");
const chai = require("chai");
const chaiHttp = require("chai-http");
const server = require("../server");
const should = chai.should();
chai.use(chaiHttp);

describe("Readings", () => {
before(() => {
//Erase the database before testing
Reading.deleteMany({});
});
describe("/POST reading", () => {
it("Should NOT ADD a reading as value is not given", done => {
let obj = { name: "bojack" };
chai
.request(server)
.post("/api/reading/new")
.send(obj)
.end((err, res) => {
res.should.have.status(500);
res.should.be.a("object");
done();
});
});
it("Should ADD a reading as value is given", done => {
let obj = { value: "3.24" };
chai
.request(server)
.post("/api/reading/new")
.send(obj)
.end((err, res) => {
res.should.have.status(201);
res.should.be.a("object");
res.body.should.be.a("object");
res.body.data.should.be.a("object");
res.body.data.should.have.property("_id");
done();
});
});
});
});