diff --git a/.github/workflows/node.js.yml b/.github/workflows/node.js.yml new file mode 100644 index 0000000..3b2630f --- /dev/null +++ b/.github/workflows/node.js.yml @@ -0,0 +1,32 @@ +# This workflow will do a clean install of node dependencies, build the source code and run tests across different versions of node +# For more information see: https://help.github.com/actions/language-and-framework-guides/using-nodejs-with-github-actions + +name: Node.js CI + +on: + push: + branches: [ master ] + pull_request: + branches: [ master ] + +jobs: + build: + + runs-on: ubuntu-latest + + strategy: + matrix: + node-version: [10.x, 12.x, 14.x] + + steps: + - uses: actions/checkout@v2 + - name: Use Node.js ${{ matrix.node-version }} + uses: actions/setup-node@v1 + with: + node-version: ${{ matrix.node-version }} + - run: npm install + - run: cp .env.example .env + - run: source .env + - run: npm run build --if-present + - run: npm run lint --if-present + - run: npm test --if-present diff --git a/app.js b/app.js index b5200aa..cb03afe 100644 --- a/app.js +++ b/app.js @@ -20,7 +20,7 @@ mongoose.connect(MONGODB_URL, {useNewUrlParser: true, useUnifiedTopology: true } process.exit(1); }); -var db = mongoose.connection; + var app = express(); //don't show the log when it is test if(process.env.NODE_ENV !== "test") { diff --git a/controllers/AuthController.js b/controllers/AuthController.js index 5fdaeb9..d1ce9b3 100644 --- a/controllers/AuthController.js +++ b/controllers/AuthController.js @@ -3,10 +3,8 @@ const { body,validationResult } = require("express-validator"); const { sanitizeBody } = require("express-validator"); //helper file to prepare responses. const apiResponse = require("../helpers/apiResponse"); -const utility = require("../helpers/utility"); const bcrypt = require("bcrypt"); const jwt = require("jsonwebtoken"); -const { constants } = require("../helpers/constants"); /** * User registration. diff --git a/controllers/DeviceController.js b/controllers/DeviceController.js deleted file mode 100644 index 0b004fb..0000000 --- a/controllers/DeviceController.js +++ /dev/null @@ -1,236 +0,0 @@ -const Device = require("../models/DeviceModel"); -const { body,validationResult } = require("express-validator"); -const { sanitizeBody } = require("express-validator"); -const apiResponse = require("../helpers/apiResponse"); -const auth = require("../middlewares/jwt"); -var mongoose = require("mongoose"); -mongoose.set("useFindAndModify", false); - -// Device Schema -function DeviceData(data) { - this.id = data._id; - this.user_id= data.userid; - this.temperature = data.temperature; - this.rh = data.rh; - this.os_ver = data.osver; - this.heater_status = data.heaterstatus; - this.createdAt = data.createdAt; -} - -/** - * Device List. - * - * @returns {Object} - */ -exports.deviceList = [ - auth, - function (req, res) { - try { - Device.find({user_id: req.user_id},"_id user_id temperature rh os_ver heater_status createdAt").then((devices)=>{ - if(devices.length > 0){ - return apiResponse.successResponseWithData(res, "Operation success", books); - }else{ - return apiResponse.successResponseWithData(res, "Operation success", []); - } - }); - } catch (err) { - //throw error in json response with status 500. - return apiResponse.ErrorResponse(res, err); - } - } -]; - -/** - * Device store. - * - * @param {string} user_id - * @param {string} temperature - * @param {string} rh - * @param {string} os_ver - * @param {string} heater_status - * - * - * @returns {Object} - */ -exports.deviceStore = [ - auth, - body("temperature", "temperature must not be empty.").isNumeric().trim(), - body("rh", "rh must not be empty.").isNumeric().trim(), - body("os_ver", "os_ver must not be empty.").isLength({ min: 1 }).trim(), - body("heater_status", "heater_status must not be empty.").isNumeric().trim(), - body("user_id", "User id must not be empty.").isNumeric().trim().custom((value,{req}) => { - return Device.findOne({user_id: req.user_id}).then(device => { - if (device) { - return Promise.reject("Device already exist"); - } - }); - }), - sanitizeBody("*").escape(), - (req, res) => { - try { - console.log("AE") - const errors = validationResult(req); - console.log(req.body) - console.log(errors.errors) - var device = new Device( - { user_id: req.body.user_id, - temperature: req.body.temperature, - rh: req.body.rh, - os_ver: req.body.os_ver, - heater_status: req.body.heater_status, - }); - if (!errors.isEmpty()) { - return apiResponse.validationErrorWithData(res, "Validation Error.", errors.array()); - } - else { - //Save device. - device.save(function (err) { - if (err) { return apiResponse.ErrorResponse(res, err); } - let bookData = new DeviceData(device); - return apiResponse.successResponseWithData(res,"Book add Success.", bookData); - }); - } - } catch (err) { - //throw error in json response with status 500. - return apiResponse.ErrorResponse(res, err); - } - } -]; - - - -/** - * Device Detail. - * - * @param {string} id - * - * @returns {Object} - */ -exports.deviceDetail = [ - auth, - function (req, res) { - if(!mongoose.Types.ObjectId.isValid(req.params.id)){ - return apiResponse.successResponseWithData(res, "Operation success", {}); - } - try { - Device.findOne({_id: req.params.id,user: req.user._id},"_id title description isbn createdAt").then((book)=>{ - if(book !== null){ - let bookData = new BookData(book); - return apiResponse.successResponseWithData(res, "Operation success", bookData); - }else{ - return apiResponse.successResponseWithData(res, "Operation success", {}); - } - }); - } catch (err) { - //throw error in json response with status 500. - return apiResponse.ErrorResponse(res, err); - } - } -]; - -/** - * Device update. - * - * @param {string} title - * @param {string} description - * @param {string} isbn - * - * @returns {Object} - */ -exports.deviceUpdate = [ - auth, - body("title", "Title must not be empty.").isLength({ min: 1 }).trim(), - body("description", "Description must not be empty.").isLength({ min: 1 }).trim(), - body("isbn", "ISBN must not be empty").isLength({ min: 1 }).trim().custom((value,{req}) => { - return Device.findOne({isbn : value,user: req.user._id, _id: { "$ne": req.params.id }}).then(book => { - if (book) { - return Promise.reject("Book already exist with this ISBN no."); - } - }); - }), - sanitizeBody("*").escape(), - (req, res) => { - try { - const errors = validationResult(req); - var book = new Book( - { title: req.body.title, - description: req.body.description, - isbn: req.body.isbn, - _id:req.params.id - }); - - if (!errors.isEmpty()) { - return apiResponse.validationErrorWithData(res, "Validation Error.", errors.array()); - } - else { - if(!mongoose.Types.ObjectId.isValid(req.params.id)){ - return apiResponse.validationErrorWithData(res, "Invalid Error.", "Invalid ID"); - }else{ - Device.findById(req.params.id, function (err, foundBook) { - if(foundBook === null){ - return apiResponse.notFoundResponse(res,"Book not exists with this id"); - }else{ - //Check authorized user - if(foundBook.user.toString() !== req.user._id){ - return apiResponse.unauthorizedResponse(res, "You are not authorized to do this operation."); - }else{ - //update book. - Device.findByIdAndUpdate(req.params.id, book, {},function (err) { - if (err) { - return apiResponse.ErrorResponse(res, err); - }else{ - let bookData = new BookData(book); - return apiResponse.successResponseWithData(res,"Book update Success.", bookData); - } - }); - } - } - }); - } - } - } catch (err) { - //throw error in json response with status 500. - return apiResponse.ErrorResponse(res, err); - } - } -]; - -/** - * Device Delete. - * - * @param {string} id - * - * @returns {Object} - */ -exports.deviceDelete = [ - auth, - function (req, res) { - if(!mongoose.Types.ObjectId.isValid(req.params.id)){ - return apiResponse.validationErrorWithData(res, "Invalid Error.", "Invalid ID"); - } - try { - Device.findById(req.params.id, function (err, foundBook) { - if(foundBook === null){ - return apiResponse.notFoundResponse(res,"Book not exists with this id"); - }else{ - //Check authorized user - if(foundBook.user.toString() !== req.user._id){ - return apiResponse.unauthorizedResponse(res, "You are not authorized to do this operation."); - }else{ - //delete book. - Device.findByIdAndRemove(req.params.id,function (err) { - if (err) { - return apiResponse.ErrorResponse(res, err); - }else{ - return apiResponse.successResponse(res,"Book delete Success."); - } - }); - } - } - }); - } catch (err) { - //throw error in json response with status 500. - return apiResponse.ErrorResponse(res, err); - } - } -]; \ No newline at end of file diff --git a/routes/api.js b/routes/api.js index 0f794d7..f9848ec 100644 --- a/routes/api.js +++ b/routes/api.js @@ -7,6 +7,5 @@ var app = express(); app.use("/auth/", authRouter); app.use("/book/", bookRouter); -app.use("/device/", deviceRouter); module.exports = app; \ No newline at end of file diff --git a/routes/device.js b/routes/device.js deleted file mode 100644 index fb18646..0000000 --- a/routes/device.js +++ /dev/null @@ -1,12 +0,0 @@ -var express = require("express"); -const DeviceController = require("../controllers/DeviceController"); - -var router = express.Router(); - -router.get("/", DeviceController.deviceList); -router.get("/:id", DeviceController.deviceDetail); -router.post("/", DeviceController.deviceStore); -router.put("/:id", DeviceController.deviceUpdate); -router.delete("/:id", DeviceController.deviceDelete); - -module.exports = router; \ No newline at end of file diff --git a/test/auth.js b/test/auth.js index 7bb4dc7..90bcfce 100644 --- a/test/auth.js +++ b/test/auth.js @@ -1,4 +1,4 @@ -const { chai, server, should } = require("./testConfig"); +const { chai, server } = require("./testConfig"); const UserModel = require("../models/UserModel"); /** @@ -14,7 +14,8 @@ describe("Auth", () => { // Before each test we empty the database before((done) => { - UserModel.deleteMany({}, (err) => { + UserModel.deleteMany({}, (err) => { + console.log(err) done(); }); }); diff --git a/test/book.js b/test/book.js index 8c809ce..f4a2c33 100644 --- a/test/book.js +++ b/test/book.js @@ -1,4 +1,4 @@ -const { chai, server, should } = require("./testConfig"); +const { chai, server } = require("./testConfig"); const BookModel = require("../models/BookModel"); /** @@ -16,6 +16,7 @@ describe("Book", () => { //Before each test we empty the database before((done) => { BookModel.deleteMany({}, (err) => { + console.log(err) done(); }); });