Skip to content
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

Feat: Logging of requests and errors #131

Open
wants to merge 2 commits into
base: newBackend
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -102,4 +102,6 @@ dist

# TernJS port file
.tern-port
/package-lock.json
/package-lock.json
/frontend
/node_modules
35 changes: 31 additions & 4 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,27 @@
require("dotenv").config({ path: "./src/env/.env" });
const chalk = require("chalk");
const express = require("express");
const cors = require("cors");
const path = require("path");
const bodyParser = require("body-parser");
const session = require("express-session");
const morgan = require("morgan");
const { app } = require("./src/helpers/timer");

app.use(
morgan((tokens, req, res) =>
[
chalk.hex("#ff4757").bold("REQUEST --> "),
chalk.hex("#34ace0").bold(tokens.method(req, res)),
chalk.hex("#ffb142").bold(tokens.status(req, res)),
chalk.bold(tokens.url(req, res)),
chalk.hex("#2ed573").bold(`${tokens["response-time"](req, res)} ms`),
chalk.hex("#f78fb3").bold(`@ ${tokens.date(req, res)}`),
chalk.yellow(tokens["remote-addr"](req, res)),
chalk.hex("#1e90ff")(tokens["user-agent"](req, res)),
].join(" ")
)
);
app.use(bodyParser.raw());
// session
app.use(
Expand All @@ -15,6 +31,7 @@ app.use(
saveUninitialized: true,
})
);

// routes

const authRouter = require("./src/api/auth");
Expand All @@ -25,12 +42,22 @@ app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use(cors());
app.use(express.static("./Frontend/build"));
app.use((req, res) => {
res.sendFile(`${__dirname}/frontend/build/index.html`);
});

// app.use((req, res, next) => {
// res.sendFile(`${__dirname}/frontend/build/index.html`);
// });
app.use("/auth", authRouter);
app.use("/api", apiRouter);
app.use((req, res) => {
// console.log(err);
// console.log("hello");
console.log(chalk.red.bold(res.locals.error.message));
return 0;
});
global.appRoot = path.resolve(__dirname);

const port = 3000;

app.listen(port, () => console.log(`server started at port ${port}`));
app.listen(port, () =>
console.log(chalk.blue.bold(`server started at port ${port}`))
);
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
"axios": "^0.21.1",
"bcrypt": "^5.0.0",
"body-parser": "^1.19.0",
"chalk": "^4.1.0",
"cors": "^2.8.5",
"countdown": "^2.6.0",
"crypto-random-string": "^3.3.0",
Expand All @@ -48,6 +49,7 @@
"http": "0.0.1-security",
"jsonwebtoken": "^8.5.1",
"mongoose": "^5.11.10",
"morgan": "^1.10.0",
"multer": "^1.4.2",
"node-cron": "^2.0.3",
"nodemailer": "^6.4.17",
Expand Down
114 changes: 60 additions & 54 deletions src/api/routers/AdminMission.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
/* eslint-disable no-await-in-loop */
const Router = require("express").Router();
const chalk = require("chalk");
const { validationResult } = require("express-validator");
const Mission = require("../../database/models/Mission");

Expand All @@ -10,74 +11,79 @@ const {
} = require("../../middlewares/expressValidator");
const { adminVerify, superAdminVerify } = require("../../middlewares/role");

Router.get("/", adminVerify, async (req, res) => {
Router.get("/", adminVerify, async (req, res, next) => {
try {
const TotalMissions = await Mission.find({});
return res.status(200).json({ Missions: TotalMissions });
} catch (err) {
console.log(err);
return res.status(500).json({
res.locals.error = err;
res.status(500).json({
message: "Server Error ",
});
}
});

Router.post("/add", superAdminVerify, MissionValidator, async (req, res) => {
try {
const {
Category,
clue,
answer_Type,
answer,
Location,
Other_Info,
MissionName,
Feed,
ServerEvaluation,
maxPoints,
Hints,
} = req.body;
Router.post(
"/add",
superAdminVerify,
MissionValidator,
async (req, res, next) => {
try {
const {
Category,
clue,
answer_Type,
answer,
Location,
Other_Info,
MissionName,
Feed,
ServerEvaluation,
maxPoints,
Hints,
} = req.body;

const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}

const newHints = [];
const newHints = [];

for (let i = 0; i < Hints.length; i++) {
const newhint = await Hint.create(Hints[i]);
newHints.push(newhint);
}
for (let i = 0; i < Hints.length; i++) {
const newhint = await Hint.create(Hints[i]);
newHints.push(newhint);
}

const m = await Mission.create({
Category,
clue,
answer_Type,
answer,
Location,
Other_Info,
maxPoints,
MissionName,
Feed,
ServerEvaluation,
assignedTeams: [],
Hints: newHints,
});
const m = await Mission.create({
Category,
clue,
answer_Type,
answer,
Location,
Other_Info,
maxPoints,
MissionName,
Feed,
ServerEvaluation,
assignedTeams: [],
Hints: newHints,
});

return res.status(200).json({ message: "mission added sucessfully" });
} catch (e) {
console.log(e);
return res.status(500).json({
message: "Server Error ",
});
return res.status(200).json({ message: "mission added sucessfully" });
} catch (e) {
res.locals.error = e;
res.status(500).json({
message: "Server Error ",
});
}
}
});
);
Router.patch(
"/update",
superAdminVerify,
UpdateMissionValidator,
async (req, res) => {
async (req, res, next) => {
try {
const { id } = req.body;

Expand All @@ -100,15 +106,15 @@ Router.patch(
await Mission.findByIdAndUpdate(mission._id, req.body);
return res.status(200).json({ message: "mission updated sucessfully" });
} catch (e) {
console.log(e);
return res.status(500).json({
res.locals.error = e;
res.status(500).json({
message: "Server Error ",
});
}
}
);

Router.delete("/delete/:id", superAdminVerify, async (req, res) => {
Router.delete("/delete/:id", superAdminVerify, async (req, res, next) => {
try {
const { id } = req.params;

Expand All @@ -124,8 +130,8 @@ Router.delete("/delete/:id", superAdminVerify, async (req, res) => {
mission.remove();
return res.status(200).json({ message: "mission deleted sucessfully" });
} catch (e) {
console.log(e);
return res.status(500).json({
res.locals.error = e;
res.status(500).json({
message: "Server Error ",
});
}
Expand Down
27 changes: 15 additions & 12 deletions src/api/routers/AdminRoute.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
const Router = require("express").Router();
const chalk = require("chalk");
const cryptoRandomString = require("crypto-random-string");
const bcrypt = require("bcrypt");
const { validationResult } = require("express-validator");
Expand All @@ -17,7 +18,7 @@ Router.post(
"/createAdmin",
AdminCreateValidator,
superAdminVerify,
async (req, res) => {
async (req, res, next) => {
try {
const issuperadmin = await User.findById(req.jwt_payload.id);
if (issuperadmin.Role !== "SuperAdmin") {
Expand Down Expand Up @@ -60,14 +61,14 @@ Router.post(
.status(401)
.json({ message: "emailId provided was undefined" });
} catch (err) {
console.log(err);
return res.status(500).json({
res.locals.error = err;
res.status(500).json({
message: "Server Error ",
});
}
}
);
Router.delete("/deleteAdmin", superAdminVerify, async (req, res) => {
Router.delete("/deleteAdmin", superAdminVerify, async (req, res, next) => {
try {
const { emailId } = req.query;

Expand All @@ -85,13 +86,13 @@ Router.delete("/deleteAdmin", superAdminVerify, async (req, res) => {
}
return res.status(401).json({ message: "emailId provided was undefined" });
} catch (err) {
console.log(err);
return res.status(500).json({
res.locals.error = err;
res.status(500).json({
message: "Server Error ",
});
}
});
Router.get("/submissions", adminVerify, async (req, res) => {
Router.get("/submissions", adminVerify, async (req, res, next) => {
try {
const activityFeeds = await Activity.find({
isSubmitted: true,
Expand All @@ -100,11 +101,12 @@ Router.get("/submissions", adminVerify, async (req, res) => {

return res.status(200).json({ submissions: activityFeeds });
} catch (error) {
console.log(error);
return res.status(500).json({ message: error.message });
res.locals.error = error;
res.status(500).json({ Message: "Server Error, Try again later" });
next();
}
});
Router.post("/accept", AcceptValidator, adminVerify, async (req, res) => {
Router.post("/accept", AcceptValidator, adminVerify, async (req, res, next) => {
try {
const { isAccepted, activityfeedId } = req.body;
const errors = validationResult(req);
Expand Down Expand Up @@ -148,8 +150,9 @@ Router.post("/accept", AcceptValidator, adminVerify, async (req, res) => {
.status(200)
.json({ message: "Answered successfully accepted or rejected" });
} catch (error) {
console.log(error);
return res.status(500).json({ message: error.message });
res.locals.error = error;
res.status(500).json({ Message: "Server Error, Try again later" });
next();
}
});

Expand Down
24 changes: 14 additions & 10 deletions src/api/routers/PlayerAuth.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
const player = require("express").Router();
const chalk = require("chalk");
const { validationResult } = require("express-validator");
const bcrypt = require("bcrypt");
const {
Expand All @@ -8,7 +9,7 @@ const User = require("../../database/models/User");
const { createJWTtoken } = require("../../middlewares/jwt");
const { send, verify } = require("../../helpers/SMS/index");

player.post("/register", playerRegisterValidator, async (req, res) => {
player.post("/register", playerRegisterValidator, async (req, res, next) => {
try {
const { name, emailId, phoneNo, password } = req.body;

Expand Down Expand Up @@ -39,15 +40,16 @@ player.post("/register", playerRegisterValidator, async (req, res) => {
return res.status(200).json({ message: "OTP sent" });
return res.status(400).json({ message: "OTP not sent" });
} catch (err) {
console.log(err.message);
res.locals.error = err;
return res.status(400).json({ message: "OTP not sent" });
}
} catch (err) {
console.log(err.message);
return res.status(500).json({ message: "Server Error, Try again later" });
res.locals.error = err;
res.status(500).json({ Message: "Server Error, Try again later" });
next();
}
});
player.post("/resendOtp", async (req, res) => {
player.post("/resendOtp", async (req, res, next) => {
try {
const { mobileNo } = req.body;
if (!mobileNo) return res.status(400).json({ message: "Fill all fields" });
Expand All @@ -58,11 +60,12 @@ player.post("/resendOtp", async (req, res) => {
return res.status(200).json({ message: "OTP sent" });
return res.status(404).json({ message: "token not provided" });
} catch (err) {
console.log(err.message);
return res.status(500).json({ message: "Server Error, Try again later" });
res.locals.error = err;
res.status(500).json({ Message: "Server Error, Try again later" });
next();
}
});
player.post("/verify", async (req, res) => {
player.post("/verify", async (req, res, next) => {
try {
const { otp, mobileNo } = req.body;
if (!otp || !mobileNo)
Expand Down Expand Up @@ -90,8 +93,9 @@ player.post("/verify", async (req, res) => {
date.setTime(date.getTime() + 86400000);
return res.status(200).json({ result, token, expiration: date });
} catch (err) {
console.log(err.message);
return res.status(500).json({ message: "Server Error, Try again later" });
res.locals.error = err;
res.status(500).json({ Message: "Server Error, Try again later" });
next();
}
});

Expand Down
Loading