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"; import { dir } from "./utils"; dotenv.config(); const origin = chalk.bold(chalk.yellow("main.js: ")); const port = +process.env.PORT ?? 8080; const contentType = { "Content-Type": "application/json" }; const fileName = dir + "data.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(fileName, JSON.stringify(data, null, 2)); 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)}`);