Browse Source

ref: random minor refactors

Sv443 4 months ago
parent
commit
10d58cc3d9
8 changed files with 53 additions and 46 deletions
  1. 10 7
      src/dev/latency-test.ts
  2. 1 1
      src/server.ts
  3. 4 5
      src/utils.ts
  4. 13 13
      test/album.spec.ts
  5. 6 2
      test/consts.ts
  6. 1 1
      test/hooks.ts
  7. 3 2
      test/search.spec.ts
  8. 15 15
      test/translations.spec.ts

+ 10 - 7
src/dev/latency-test.ts

@@ -106,17 +106,20 @@ async function run() {
 
   const reportTimes = {} as Partial<LatencyTestReport["times"]>;
 
-  const logVal = (label: string, value: Stringifiable, kleurFunc?: (str: string) => void) => {
-    const valStr = `${label}:\t${String(value).padStart(4, " ")} ms`;
-    reportTimes[label as keyof LatencyTestReport["times"]] = Number(value);
+  const logVal = (label?: string, value?: Stringifiable, kleurFunc?: (str: string) => void) => {
+    let valStr = label ?? "";
+    if(value) {
+      valStr += `:\t${String(value).padStart(4, " ")} ms`;
+      reportTimes[label as keyof LatencyTestReport["times"]] = Number(value);
+    }
     console.log(kleurFunc ? kleurFunc(valStr) : valStr);
   }
 
   const testFinishTs = Date.now();
   const totalTime = Number(((testFinishTs - testStartTs) / 1000).toFixed(2));
 
-  console.log(`\n>>> Latency test finished sending ${successRequests} successful requests after ${totalTime}s - Results:`);
-  console.log();
+  logVal(`\n>>> Latency test finished sending ${successRequests} successful requests after ${totalTime}s - Results:`);
+  logVal();
   logVal("5th%", getPerc(5, times), k.gray);
   logVal("10th%", getPerc(10, times), k.gray);
   logVal("25th%", getPerc(25, times), k.gray);
@@ -126,11 +129,11 @@ async function run() {
   logVal("97th%", getPerc(97, times), k.bold);
   logVal("98th%", getPerc(98, times));
   logVal("99th%", getPerc(99, times));
-  console.log();
+  logVal();
   logVal("min", min);
   logVal("avg", avg, k.bold);
   logVal("max", max);
-  console.log();
+  logVal();
 
   const getFormattedDate = (timestamp: number) => Intl.DateTimeFormat(Intl.DateTimeFormat().resolvedOptions().locale, {
     dateStyle: "short",

+ 1 - 1
src/server.ts

@@ -112,7 +112,7 @@ export async function init() {
   const listener = app.listen(port, host, () => {
     registerRoutes();
 
-    console.log(k.green(`Listening on ${host}:${port}\n`));
+    console.log(k.green(`geniURL is listening on ${host}:${port}\n`));
   });
 
   listener.on("error", (err) => error("General server error", err, true));

+ 4 - 5
src/utils.ts

@@ -21,11 +21,10 @@ export function paramValid(val: unknown): boolean {
  * @param matchesAmt Amount of matches / datasets returned in this response
  */
 export function respond(res: Response, typeOrStatusCode: ResponseType | number, data: Stringifiable | Record<string, unknown>, format: ResponseFormat | string = "json", matchesAmt?: number) {
-  let statusCode = 500;
-  let error = true;
-  let matches = null;
-
-  let resData = {};
+  let error = true,
+    matches = null,
+    statusCode = 500,
+    resData = {};
 
   if(!(format in mimeTypeMap))
     format = "json";

+ 13 - 13
test/album.spec.ts

@@ -1,6 +1,19 @@
 import { checkAlbumProps, checkArtistProps, sendReq } from "./hooks";
 
 describe("Album routes", () => {
+  //#region inv /album
+
+  it("Album path without ID yields error", async () => {
+    const { res, status } = await sendReq("/album");
+    const body = await res.json();
+
+    expect(status).toBe(400);
+
+    expect(body?.error).toEqual(true);
+    expect(body?.matches).toEqual(null);
+    expect(body?.message).toBeDefined();
+  });
+
   //#region /album/:id
 
   it("Album details yields correct props", async () => {
@@ -29,17 +42,4 @@ describe("Album routes", () => {
     expect(body?.matches).toEqual(0);
     expect(body?.message).toBeUndefined();
   });
-
-  //#region inv /album
-
-  it("Album path without ID yields error", async () => {
-    const { res, status } = await sendReq("/album");
-    const body = await res.json();
-
-    expect(status).toBe(400);
-
-    expect(body?.error).toEqual(true);
-    expect(body?.matches).toEqual(null);
-    expect(body?.message).toBeDefined();
-  });
 });

+ 6 - 2
test/constants.ts → test/consts.ts

@@ -2,11 +2,15 @@ import "dotenv/config";
 
 export const baseUrl = `http://127.0.0.1:${process.env.HTTP_PORT}/v2`;
 
+/** Max results that can be returned by geniURL - should be consistent with `maxResultsAmt` in `src/constants.ts` */
+export const maxResultsAmt = 10;
+
+/** Auth token for local testing */
 const authToken = process.env.AUTH_TOKENS?.split(",")[0];
 
-export const defaultFetchOpts: Partial<RequestInit> = {
+export const defaultFetchOpts = {
   method: "GET",
   headers: {
     ...(authToken ? { "Authentication": `Bearer ${authToken}` } : {}),
   },
-};
+} as const satisfies RequestInit;

+ 1 - 1
test/hooks.ts

@@ -1,4 +1,4 @@
-import { baseUrl, defaultFetchOpts } from "./constants";
+import { baseUrl, defaultFetchOpts } from "./consts";
 
 //#region validate objects
 

+ 3 - 2
test/search.spec.ts

@@ -1,6 +1,7 @@
 import { randomBytes } from "crypto";
 import { XMLParser } from "fast-xml-parser";
 import { checkSongProps, sendReq } from "./hooks";
+import { maxResultsAmt } from "./consts";
 
 describe("Search routes", () => {
   //#region /search/top
@@ -37,14 +38,14 @@ describe("Search routes", () => {
 
   //#region /search
 
-  it("Regular search yields <=10 results", async () => {
+  it(`Regular search yields <=${maxResultsAmt} results`, async () => {
     const { res, status } = await sendReq("/search?q=Lil Nas X");
     const body = await res.json();
 
     expect(status).toBe(200);
 
     expect(body?.error).toEqual(false);
-    expect(body?.matches).toBeLessThanOrEqual(10);
+    expect(body?.matches).toBeLessThanOrEqual(maxResultsAmt);
 
     checkSongProps(body?.top);
 

+ 15 - 15
test/translations.spec.ts

@@ -1,7 +1,20 @@
 import { checkTranslationProps, sendReq } from "./hooks";
 
 describe("Translation routes", () => {
-  //#region /translations/:id
+  //#region inv /tr
+
+  it("Translations path without ID yields error", async () => {
+    const { res, status } = await sendReq("/translations");
+    const body = await res.json();
+
+    expect(status).toBe(400);
+
+    expect(body?.error).toEqual(true);
+    expect(body?.matches).toEqual(null);
+    expect(body?.message).toBeDefined();
+  });
+
+  //#region /tr/:id
 
   it("Translation yields correct props", async () => {
     const { res, status } = await sendReq("/translations/7105950");
@@ -17,7 +30,7 @@ describe("Translation routes", () => {
     body?.translations?.forEach((tr: unknown) => checkTranslationProps(tr));
   });
 
-  //#region inv /translations/:id
+  //#region inv /tr/:id
 
   it("Invalid song ID yields no matches", async () => {
     const { res, status } = await sendReq("/translations/0");
@@ -29,17 +42,4 @@ describe("Translation routes", () => {
     expect(body?.matches).toEqual(0);
     expect(body?.message).toBeUndefined();
   });
-
-  //#region inv /translations
-
-  it("Translations path without ID yields error", async () => {
-    const { res, status } = await sendReq("/translations");
-    const body = await res.json();
-
-    expect(status).toBe(400);
-
-    expect(body?.error).toEqual(true);
-    expect(body?.matches).toEqual(null);
-    expect(body?.message).toBeDefined();
-  });
 });