Create more utils: logger and responder

This commit is contained in:
powermaker450 2024-08-18 17:11:15 -04:00
parent d68d780951
commit 561e95c255
7 changed files with 45 additions and 25 deletions

View file

@ -5,8 +5,10 @@
"main": "./dist/main.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "tsc -p .",
"start": "node ./dist/main.js"
"clean": "rm -rf ./dist",
"build": "pnpm clean && tsc -p .",
"start": "node ./dist/main.js",
"clean-start": "pnpm build && pnpm start"
},
"keywords": [],
"author": "",

View file

@ -1,13 +1,15 @@
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 { checkFile, emp, Logger, Responder } from "./utils";
dotenv.config();
const origin = chalk.bold(chalk.yellow("main.js: "));
const logger = new Logger();
const response = new Responder();
// @ts-ignore
const port = +process.env.PORT ?? 8080;
const host = emp(`http://localhost:${port}`);
const contentType = { "Content-Type": "application/json" };
http
@ -15,6 +17,7 @@ http
const isPost = req.method === "POST";
req.on("data", async (chunk) => {
const sender = req.headers["user-agent"];
let data: Review[] = checkFile("data.json", "utf8");
let temp: any;
@ -29,10 +32,7 @@ http
.validate(temp)
.then((valid) => {
req.on("end", () => {
console.log(
origin + `${chalk.green(req.headers["user-agent"])} sent:`,
valid,
);
logger.log(`${emp(sender)} sent: ${valid}`);
data.push(valid);
fs.writeFileSync(
@ -40,31 +40,31 @@ http
JSON.stringify(data, null, 2),
);
res.writeHead(200, contentType);
res.write("OK");
res.writeHead(201, contentType);
res.write(response.success("Review was sent"));
res.end();
});
})
.catch((error) => {
console.error(error);
.catch((err) => {
logger.error(err);
res.writeHead(415, contentType);
res.write(JSON.stringify({ error: "Invalid content type." }));
res.write(JSON.stringify({ response: "error", message: "Invalid content-type." }));
res.end();
});
});
req.on("end", () => {
const sender = req.headers["user-agent"];
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." }));
logger.warn(`${emp(sender)} sent no data.`)
res.writeHead(400, contentType);
res.write(response.error("Invalid content-type"));
res.end();
}
});
})
.listen(port || 8080);
console.log(origin + `Server started on port ${chalk.green(port)}`);
logger.log(`Server started on ${host}`);

View file

@ -1,2 +1,3 @@
export * from "./functions";
export * from "./logger";
export * from "./utils";
export * from "./responder";

View file

@ -12,19 +12,19 @@ export class Logger {
this._main = chalk.bold.gray("[Simple Review Server] ");
}
log(text: any, args?: any): void {
public log(text: any, args?: any): void {
args
? console.log(this._main + text, args)
: console.log(this._main + text);
}
warn(text: any, args?: any): void {
public warn(text: any, args?: any): void {
args
? console.warn(this._wrn + this._main + text, args)
: console.warn(this._wrn + this._main + text);
}
error(text: any, args?: any): void {
public error(text: any, args?: any): void {
args
? console.error(this._err + this._main + text, args)
: console.error(this._err + this._main + text);

17
src/utils/responder.ts Normal file
View file

@ -0,0 +1,17 @@
export class Responder {
constructor() {}
public success(message: string): string {
return JSON.stringify({
response: "success",
message: message
});
}
public error(message: string): string {
return JSON.stringify({
response: "error",
message: message
})
}
}

View file

@ -11,7 +11,7 @@
// "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
/* Language and Environment */
"target": "es2016", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
"target": "es2021", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
// "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
// "jsx": "preserve", /* Specify what JSX code is generated. */
// "experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */