From 561e95c255520a641a99c7d3f25ed74dc63874bd Mon Sep 17 00:00:00 2001 From: powermaker450 Date: Sun, 18 Aug 2024 17:11:15 -0400 Subject: [PATCH] Create more utils: logger and responder --- package.json | 6 +++-- src/main.ts | 36 ++++++++++++++-------------- src/utils/{utils.ts => functions.ts} | 0 src/utils/index.ts | 3 ++- src/utils/logger.ts | 6 ++--- src/utils/responder.ts | 17 +++++++++++++ tsconfig.json | 2 +- 7 files changed, 45 insertions(+), 25 deletions(-) rename src/utils/{utils.ts => functions.ts} (100%) create mode 100644 src/utils/responder.ts diff --git a/package.json b/package.json index 7fa1e96..4f52d16 100644 --- a/package.json +++ b/package.json @@ -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": "", diff --git a/src/main.ts b/src/main.ts index d88d940..f1dad36 100644 --- a/src/main.ts +++ b/src/main.ts @@ -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}`); diff --git a/src/utils/utils.ts b/src/utils/functions.ts similarity index 100% rename from src/utils/utils.ts rename to src/utils/functions.ts diff --git a/src/utils/index.ts b/src/utils/index.ts index e3f1461..5b9a3cf 100644 --- a/src/utils/index.ts +++ b/src/utils/index.ts @@ -1,2 +1,3 @@ +export * from "./functions"; export * from "./logger"; -export * from "./utils"; +export * from "./responder"; diff --git a/src/utils/logger.ts b/src/utils/logger.ts index 97a40d7..8f54159 100644 --- a/src/utils/logger.ts +++ b/src/utils/logger.ts @@ -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); diff --git a/src/utils/responder.ts b/src/utils/responder.ts new file mode 100644 index 0000000..b7f23c0 --- /dev/null +++ b/src/utils/responder.ts @@ -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 + }) + } +} diff --git a/tsconfig.json b/tsconfig.json index ebefe93..e56412a 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -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. */