Accept data only at /post
This commit is contained in:
parent
d865b56c63
commit
14791149c6
72
src/main.ts
72
src/main.ts
|
@ -15,52 +15,58 @@ const contentType = { "Content-Type": "application/json" };
|
|||
http
|
||||
.createServer((req, res) => {
|
||||
const isPost = req.method === "POST";
|
||||
const sender = emp(req.headers["user-agent"]);
|
||||
|
||||
req.on("data", async (chunk) => {
|
||||
const sender = emp(req.headers["user-agent"]);
|
||||
let data: Review[] = checkFile("data.json", "utf8");
|
||||
let temp: any;
|
||||
|
||||
try {
|
||||
temp = JSON.parse(chunk);
|
||||
} catch (err) {
|
||||
console.error(origin + "Chunk is not valid JSON");
|
||||
return;
|
||||
}
|
||||
if (req.url === "/post") {
|
||||
let data: Review[] = checkFile("data.json", "utf8");
|
||||
let temp: any;
|
||||
|
||||
await reviewSchema
|
||||
.validate(temp)
|
||||
.then((valid) => {
|
||||
req.on("end", () => {
|
||||
logger.log(`${sender} sent:`, valid);
|
||||
try {
|
||||
temp = JSON.parse(chunk);
|
||||
} catch (err) {
|
||||
console.error(origin + "Chunk is not valid JSON");
|
||||
return;
|
||||
}
|
||||
|
||||
data.push(valid);
|
||||
fs.writeFileSync(
|
||||
"./persist/data.json",
|
||||
JSON.stringify(data, null, 2),
|
||||
);
|
||||
await reviewSchema
|
||||
.validate(temp)
|
||||
.then((valid) => {
|
||||
req.on("end", () => {
|
||||
logger.log(`${sender} sent:`, valid);
|
||||
|
||||
res.writeHead(201, contentType);
|
||||
res.write(response.success("Review was sent"));
|
||||
data.push(valid);
|
||||
fs.writeFileSync(
|
||||
"./persist/data.json",
|
||||
JSON.stringify(data, null, 2),
|
||||
);
|
||||
|
||||
res.writeHead(201, contentType);
|
||||
res.write(response.success("Review was sent"));
|
||||
res.end();
|
||||
});
|
||||
})
|
||||
.catch((err) => {
|
||||
logger.error(err);
|
||||
|
||||
res.writeHead(400, contentType);
|
||||
res.write(JSON.stringify({ response: "error", message: "Invalid content-type." }));
|
||||
res.end();
|
||||
});
|
||||
})
|
||||
.catch((err) => {
|
||||
logger.error(err);
|
||||
} else {
|
||||
logger.log(`${sender} cannot ${req.method} to ${req.url}`);
|
||||
|
||||
res.writeHead(415, contentType);
|
||||
res.write(JSON.stringify({ response: "error", message: "Invalid content-type." }));
|
||||
res.end();
|
||||
});
|
||||
res.writeHead(400, contentType);
|
||||
res.write(response.error(`Cannot ${req.method} to '${req.url}'`));
|
||||
res.end();
|
||||
}
|
||||
});
|
||||
|
||||
req.on("end", () => {
|
||||
const sender = emp(req.headers["user-agent"]);
|
||||
if (!isPost) {
|
||||
logger.log(`${sender} sent no data.`)
|
||||
|
||||
res.writeHead(400, contentType);
|
||||
res.write(response.error("Invalid content-type"));
|
||||
res.writeHead(404, {"Content-Type": "text/plain"});
|
||||
res.write(`Cannot ${req.method} ${req.url}`);
|
||||
res.end();
|
||||
}
|
||||
});
|
||||
|
|
Loading…
Reference in a new issue