Commit ecbfea3d authored by Sandeep Fernando's avatar Sandeep Fernando

updated api with new endpoints

parent a8de8e2b
const express = require("express");
const cors = require("cors");
const helmet = require("helmet");
const compression = require("compression");
const app = express();
const port = process.env.PORT || 5000;
app.use(cors());
app.use(helmet());
app.use(compression());
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.get("*", (req, res) => {
res.status(200).send("garbage api is online.");
});
app.listen(port, () => {
console.log("garbage api is online.");
});
......@@ -2,5 +2,6 @@
"verbose": false,
"ignore": [],
"execMap": {},
"watch": ["./index.js"]
"watch": ["./server"],
"exec" : "node ./server/index.js"
}
\ No newline at end of file
This diff is collapsed.
......@@ -4,7 +4,7 @@
"description": "REST API for Garbage",
"main": "index.js",
"scripts": {
"start": "node index.js",
"start": "node ./server/index.js",
"dev": "nodemon"
},
"keywords": [
......@@ -18,10 +18,14 @@
"nodemon": "^2.0.7"
},
"dependencies": {
"bcrypt": "^5.0.1",
"compression": "^1.7.4",
"cors": "^2.8.5",
"express": "^4.17.1",
"express-fileupload": "^1.2.1",
"helmet": "^4.6.0",
"mongoose": "^5.12.7"
"mongoose": "^5.13.0",
"multer": "^1.4.2",
"socket.io": "^4.1.2"
}
}
const port = 5000;
const mongoUri = "mongodb://localhost:27017/garbage-detection";
module.exports = {
port,
mongoUri
}
\ No newline at end of file
const path = require("path");
const fileUpload = (req, res) => {
let sampleFile;
let uploadPath;
if (!req.files || Object.keys(req.files).length === 0) {
return res.status(400).send('No files were uploaded.');
}
sampleFile = req.files.fileName;
uploadPath = path.join(__dirname, `../public/uploads/${sampleFile.name}`);
sampleFile.mv(uploadPath, function (err) {
if (err) {
return res.status(500).send(err);
}
return res.status(200).json({
data: {
status: "SUCCESS",
filename: sampleFile.name
}
});
});
}
module.exports = {
fileUpload
}
const { LocationModel } = require("../models/location.model");
const createLocation = async (req, res) => {
const formData = {
longitude: req.body.longitude,
latitude: req.body.latitude,
}
try {
const createdLocation = await LocationModel.create(formData);
res.status(201).json({ data: createdLocation });
} catch (error) {
res.status(500).json({ errors: error });
}
}
const getAllLocations = async (req, res) => {
try {
const locations = await LocationModel.find();
res.status(200).json({ data: locations });
} catch (error) {
res.status(500).json({ errors: error });
}
}
const getLocationById = async (req, res) => {
try {
const location = await LocationModel.findOne({ _id: req.params.id })
.select("_id longitude latitude created_at updated_at");
if (location) {
res.status(200).json({ data: location });
} else {
res.status(404).json({ error: "Location not found " });
}
} catch (error) {
res.status(500).json({ errors: error });
}
}
const updateLocation = async (req, res) => {
const formData = {
longitude: req.body.longitude,
latitude: req.body.latitude,
}
if (!req.body.longitude) {
delete formData.longitude;
}
if (!req.body.latitude) {
delete formData.latitude;
}
try {
const location = await LocationModel.findOne({ _id: req.params.id });
if (location) {
let updatedLocation = Object.assign(location, formData);
updatedLocation = await updatedLocation.save();
res.status(200).json({ data: updatedLocation });
} else {
res.status(404).json({ error: "Location not found " });
}
} catch (error) {
res.status(500).json({ errors: error });
}
}
const deleteLocation = async (req, res) => {
try {
const location = await LocationModel.findOne({ _id: req.params.id });
if (location) {
await LocationModel.deleteOne({ _id: req.params.id });
res.status(204).json({ data: {} });
} else {
res.status(404).json({ error: "Location not found " });
}
} catch (error) {
res.status(500).json({ errors: error });
}
}
module.exports = {
createLocation,
getAllLocations,
getLocationById,
updateLocation,
deleteLocation,
}
\ No newline at end of file
const bcrypt = require("bcrypt");
const { UserModel } = require("../models/user.model");
const createUser = async (req, res) => {
const formData = {
full_name: req.body.full_name,
email: req.body.email,
password: bcrypt.hashSync(req.body.password, 10),
}
try {
const createdUser = await UserModel.create(formData);
res.status(201).json({ data: createdUser });
} catch (error) {
res.status(500).json({ errors: error });
}
}
const getAllUsers = async (req, res) => {
try {
const users = await UserModel.find();
res.status(200).json({ data: users });
} catch (error) {
res.status(500).json({ errors: error });
}
}
const getUserById = async (req, res) => {
try {
const user = await UserModel.findOne({ _id: req.params.id })
.select("_id full_name email created_at updated_at");
if (user) {
res.status(200).json({ data: user });
} else {
res.status(404).json({ error: "User not found " });
}
} catch (error) {
res.status(500).json({ errors: error });
}
}
const updateUser = async (req, res) => {
const formData = {
full_name: req.body.full_name,
email: req.body.email,
updated_at: new Date()
}
if (!req.body.full_name) {
delete formData.full_name;
}
if (!req.body.email) {
delete formData.email;
}
try {
const user = await UserModel.findOne({ _id: req.params.id });
if (user) {
let updatedUser = Object.assign(user, formData);
updatedUser = await updatedUser.save();
res.status(200).json({ data: updatedUser });
} else {
res.status(404).json({ error: "User not found " });
}
} catch (error) {
res.status(500).json({ errors: error });
}
}
const deleteUser = async (req, res) => {
try {
const user = await UserModel.findOne({ _id: req.params.id });
if (user) {
await UserModel.deleteOne({ _id: req.params.id });
res.status(204).json({ data: {} });
} else {
res.status(404).json({ error: "User not found " });
}
} catch (error) {
res.status(500).json({ errors: error });
}
}
module.exports = {
createUser,
getAllUsers,
getUserById,
updateUser,
deleteUser
}
\ No newline at end of file
const express = require("express");
const compression = require("compression");
const cors = require("cors");
const helmet = require("helmet");
const fileupload = require("express-fileupload");
const mongoose = require("mongoose");
const http = require("http");
const path = require("path");
// Importing Configs
const { port, mongoUri } = require("./configs/configs");
// Importing routes
const userRoutes = require("./routes/user.routes");
const locationRoutes = require("./routes/location.routes");
const fileUploadRoutes = require("./routes/file-upload.routes");
// Initialize
const app = express();
const server = http.createServer(app);
// Configuring middlewares
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(compression());
app.use(cors());
app.use(helmet());
app.use(fileupload());
app.use("/public", express.static(path.join(__dirname, "public")));
// Configuring routes
app.use("/api/users", userRoutes.router);
app.use("/api/locations", locationRoutes.router);
app.use("/api/uploads", fileUploadRoutes.router);
// Web route
app.get("*", (req, res) => {
res.status(200).send("Garbage Detection System");
})
// Connecting to Database
mongoose.connect(mongoUri, { useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true })
.then((result) => {
console.log("DB Connection has established");
})
.catch((err) => {
console.log(`Unable to connect to the DB: ${err}`);
})
// Starting the Server
server.listen(port, () => {
console.log(`Server has started on ${port}`);
})
\ No newline at end of file
const mongoose = require("mongoose");
const LocationSchema = mongoose.Schema({
longitude: {
type: String,
required: "Longitude is required",
},
latitude: {
type: String,
required: "Latitude is required",
},
created_at: {
type: Date,
default: Date.now
},
updated_at: {
type: Date,
}
});
module.exports = {
"LocationModel": mongoose.model("Location", LocationSchema)
}
const mongoose = require("mongoose");
const UserSchema = mongoose.Schema({
full_name: {
type: String,
required: "Full Name is required"
},
email: {
type: String,
required: "Email is required",
unique: "Email is already exists"
},
password: {
type: String,
required: "Password is required",
},
created_at: {
type: Date,
default: Date.now
},
updated_at: {
type: Date,
}
});
module.exports = {
"UserModel": mongoose.model("User", UserSchema)
}
const express = require("express");
const fileUploadCtrl = require("../controllers/file-upload.controller");
const router = express.Router();
router.route("/")
.post(fileUploadCtrl.fileUpload);
module.exports = {
router
}
const express = require("express");
const locationCtrl = require("../controllers/location.controller");
const router = express.Router();
router.route("/")
.post(locationCtrl.createLocation)
.get(locationCtrl.getAllLocations);
router.route("/:id")
.get(locationCtrl.getLocationById)
.put(locationCtrl.updateLocation)
.delete(locationCtrl.deleteLocation);
module.exports = {
router
}
\ No newline at end of file
const express = require("express");
const userCtrl = require("../controllers/user.controller");
const router = express.Router();
router.route("/")
.post(userCtrl.createUser)
.get(userCtrl.getAllUsers);
router.route("/:id")
.get(userCtrl.getUserById)
.put(userCtrl.updateUser)
.delete(userCtrl.deleteUser);
module.exports = {
router
}
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment