My Goal Is
If have find any data findOne() function update current endpoint with content, if not create a new element with Schema.
Problem
If no data in db, so first if it throw me ERR_HTTP_HEADERS_SENT with console.log = 1 but if have, all in well with console.log = 3.
try {
const find = await endPointSchema.findOne({ uuid: uuid });
if (!find) {
const data = new endPointSchema({
uuid: uuid,
endpoint: [{ point: Endpoint, Content }],
date: Date.now(),
});
await data.save();
console.log(1);
res.status(200).json({ message: "Succesfully Created new Breakpoint" });
return;
} else {
if (!find.endpoint) {
console.log(2);
res.end();
return;
} else {
console.log(3);
res.end();
return;
}
}
} catch (e) {
console.log(e);
res.end();
return;
}
My Endpoint
route.post("/endpoint", AuthorizePanel, async (req, res) => {
const { role, username, uuid } = req.user;
if (!role && !username && !uuid) {
res.sendStatus(401);
return;
}
const { Endpoint, Content } = req.body;
if (Endpoint === username) {
res.status(403).json({ message: "Endpoint can not be same with your username!" });
return;
}
try {
const find = await endPointSchema.findOne({ uuid: uuid });
if (!find) {
const data = new endPointSchema({
uuid: uuid,
endpoint: [{ point: Endpoint, Content }],
date: Date.now(),
});
await data.save();
console.log(1);
res.status(200).json({ message: "Succesfully Created new Breakpoint" });
return;
} else {
if (!find.endpoint) {
console.log(2);
res.end();
return;
} else {
console.log(3);
res.end();
return;
}
}
} catch (e) {
console.log(e);
res.end();
return;
}
});
authorizePanel
import jwt from "jsonwebtoken";
export const AuthorizePanel = (req, res, next) => {
const authHeader = req.headers.authorization;
if (authHeader) {
const token = authHeader.split(" ")[1];
jwt.verify(token, process.env.JWT_SECRET, (err, user) => {
if (err) {
res.sendStatus(403)
return
}
req.user = user;
next();
});
}
next();
};