simple-review-server/src/main.ts

71 lines
1.8 KiB
TypeScript
Raw Normal View History

2024-08-16 15:04:52 -04:00
import chalk from "chalk";
import fs from "fs";
import http from "http";
import dotenv from "dotenv";
import { Review, reviewSchema } from "./types";
import { checkFile } from "./utils";
dotenv.config();
const origin = chalk.bold(chalk.yellow("main.js: "));
const port = +process.env.PORT ?? 8080;
const contentType = { "Content-Type": "application/json" };
http
.createServer((req, res) => {
const isPost = req.method === "POST";
req.on("data", async (chunk) => {
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;
}
await reviewSchema
.validate(temp)
.then((valid) => {
req.on("end", () => {
console.log(
origin + `${chalk.green(req.headers["user-agent"])} sent:`,
valid,
);
data.push(valid);
fs.writeFileSync(
"./persist/data.json",
JSON.stringify(data, null, 2),
);
2024-08-16 15:04:52 -04:00
res.writeHead(200, contentType);
res.write("OK");
res.end();
});
})
.catch((error) => {
console.error(error);
res.writeHead(415, contentType);
res.write(JSON.stringify({ error: "Invalid content type." }));
res.end();
});
});
req.on("end", () => {
if (!isPost) {
console.log(
origin + `${chalk.green(req.headers["user-agent"])} sent no body.`,
);
res.writeHead(415, contentType);
res.write(JSON.stringify({ error: "Invalid content type." }));
res.end();
}
});
})
.listen(port || 8080);
console.log(origin + `Server started on port ${chalk.green(port)}`);