Skip to content

Commit

Permalink
ref: change indent size
Browse files Browse the repository at this point in the history
  • Loading branch information
Sv443 committed Jul 9, 2023
1 parent 396fe96 commit 03dc9a7
Show file tree
Hide file tree
Showing 13 changed files with 593 additions and 607 deletions.
8 changes: 4 additions & 4 deletions src/axios.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import { default as _axios } from "axios";

export const axios = _axios.create({
timeout: 1000 * 15,
timeout: 1000 * 15,
});

export function getAxiosAuthConfig(authToken?: string) {
return authToken ? {
headers: { "Authorization": `Bearer ${authToken}` },
} : {};
return authToken ? {
headers: { "Authorization": `Bearer ${authToken}` },
} : {};
}
14 changes: 7 additions & 7 deletions src/constants.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
import type { IRateLimiterOptions } from "rate-limiter-flexible";

export const rateLimitOptions: IRateLimiterOptions = {
points: 25,
duration: 30,
points: 25,
duration: 30,
};

/** Set of all supported [ISO 639-1 language codes](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) */
export const langCodes = new Set<string>(["aa","ab","ae","af","ak","am","an","ar","as","av","ay","az","ba","be","bg","bh","bi","bm","bn","bo","br","bs","ca","ce","ch","co","cr","cs","cu","cv","cy","da","de","dv","dz","ee","el","en","eo","es","et","eu","fa","ff","fi","fj","fo","fr","fy","ga","gd","gl","gn","gu","gv","ha","he","hi","ho","hr","ht","hu","hy","hz","ia","id","ie","ig","ii","ik","io","is","it","iu","ja","jv","ka","kg","ki","kj","kk","kl","km","kn","ko","kr","ks","ku","kv","kw","ky","la","lb","lg","li","ln","lo","lt","lu","lv","mg","mh","mi","mk","ml","mn","mr","ms","mt","my","na","nb","nd","ne","ng","nl","nn","no","nr","nv","ny","oc","oj","om","or","os","pa","pi","pl","ps","pt","qu","rm","rn","ro","ru","rw","sa","sc","sd","se","sg","si","sk","sl","sm","sn","so","sq","sr","ss","st","su","sv","sw","ta","te","tg","th","ti","tk","tl","tn","to","tr","ts","tt","tw","ty","ug","uk","ur","uz","ve","vi","vo","wa","wo","xh","yi","yo","za","zh","zu"]);

/** Map of unicode variant characters and replacements used in normalizing fields before fuzzy filtering them */
export const charReplacements = new Map<string, string>([
["`´’︐︑ʻ", "'"],
["“”", "\""],
[",", ","],
["—─ ", "-"],
["     ", " "],
["`´’︐︑ʻ", "'"],
["“”", "\""],
[",", ","],
["—─ ", "-"],
["     ", " "],
]);
11 changes: 5 additions & 6 deletions src/error.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,10 @@ import k from "kleur";
* @param err Error instance that caused the error
* @param fatal Exits with code 1 if set to true
*/
export function error(msg: string, err?: Error, fatal = false)
{
console.error("\n");
console.error(k.red(msg));
err && console.error(err);
export function error(msg: string, err?: Error, fatal = false) {
console.error("\n");
console.error(k.red(msg));
err && console.error(err);

fatal && process.exit(1);
fatal && process.exit(1);
}
31 changes: 15 additions & 16 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,24 +5,23 @@ import { error } from "./error";

const { env } = process;

async function init()
{
try
{
const missingEnvVars = [
"HTTP_PORT",
"GENIUS_ACCESS_TOKEN",
].reduce<string[]>((a, v) => ((typeof env[v] !== "string" || env[v]!.length < 1) ? a.concat(v) : a), []);
async function init() {
try
{
const missingEnvVars = [
"HTTP_PORT",
"GENIUS_ACCESS_TOKEN",
].reduce<string[]>((a, v) => ((typeof env[v] !== "string" || env[v]!.length < 1) ? a.concat(v) : a), []);

if(missingEnvVars.length > 0)
throw new TypeError(`Missing environment variable(s):\n- ${missingEnvVars.join("\n- ")}`);
if(missingEnvVars.length > 0)
throw new TypeError(`Missing environment variable(s):\n- ${missingEnvVars.join("\n- ")}`);

await server.init();
}
catch(err)
{
error("Error while initializing", err instanceof Error ? err : undefined, true);
}
await server.init();
}
catch(err)
{
error("Error while initializing", err instanceof Error ? err : undefined, true);
}
}

init();
42 changes: 20 additions & 22 deletions src/routes/album.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,33 +3,31 @@ import { paramValid, respond } from "../utils";
import { getAlbum } from "../songData";

export function initAlbumRoutes(router: Router) {
router.get("/album", (req, res) => {
const format: string = req.query.format ? String(req.query.format) : "json";
router.get("/album", (req, res) => {
const format: string = req.query.format ? String(req.query.format) : "json";

return respond(res, "clientError", "No song ID provided", format);
});
return respond(res, "clientError", "No song ID provided", format);
});

router.get("/album/:songId", async (req, res) => {
try
{
const { songId } = req.params;
const { format: fmt } = req.query;
router.get("/album/:songId", async (req, res) => {
try {
const { songId } = req.params;
const { format: fmt } = req.query;

const format: string = fmt ? String(fmt) : "json";
const format: string = fmt ? String(fmt) : "json";

if(!paramValid(songId) || isNaN(Number(songId)))
return respond(res, "clientError", "Provided song ID is invalid", format);
if(!paramValid(songId) || isNaN(Number(songId)))
return respond(res, "clientError", "Provided song ID is invalid", format);

const album = await getAlbum(Number(songId));
const album = await getAlbum(Number(songId));

if(!album)
return respond(res, "clientError", "Couldn't find any associated album for this song", format, 0);
if(!album)
return respond(res, "clientError", "Couldn't find any associated album for this song", format, 0);

return respond(res, "success", { album }, format, 1);
}
catch(err)
{
return respond(res, "serverError", `Encountered an internal server error: ${err instanceof Error ? err.message : ""}`, "json");
}
});
return respond(res, "success", { album }, format, 1);
}
catch(err) {
return respond(res, "serverError", `Encountered an internal server error: ${err instanceof Error ? err.message : ""}`, "json");
}
});
}
16 changes: 8 additions & 8 deletions src/routes/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,19 +6,19 @@ import { initSearchRoutes } from "./search";
import { initTranslationsRoutes } from "./translations";

const routeFuncs: ((router: Router) => unknown)[] = [
initSearchRoutes,
initTranslationsRoutes,
initAlbumRoutes,
initSearchRoutes,
initTranslationsRoutes,
initAlbumRoutes,
];

const router = Router();

export function initRouter(app: Application) {
for(const initRoute of routeFuncs)
initRoute(router);
for(const initRoute of routeFuncs)
initRoute(router);

// redirect to GitHub page
router.get("/", (_req, res) => res.redirect(packageJson.homepage));
// redirect to GitHub page
router.get("/", (_req, res) => res.redirect(packageJson.homepage));

app.use("/", router);
app.use("/", router);
}
122 changes: 58 additions & 64 deletions src/routes/search.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,78 +4,72 @@ import { getMeta } from "../songData";
import { langCodes } from "../constants";

export function initSearchRoutes(router: Router) {
router.get("/search", async (req, res) => {
try
{
const { q, artist, song, format: fmt, threshold: thr, preferLang: prLang } = req.query;
router.get("/search", async (req, res) => {
try {
const { q, artist, song, format: fmt, threshold: thr, preferLang: prLang } = req.query;

const format: string = fmt ? String(fmt) : "json";
const threshold = isNaN(Number(thr)) ? undefined : Number(thr);
const preferLang = paramValid(prLang) && langCodes.has(prLang.toLowerCase()) ? prLang.toLowerCase() : undefined;
const format: string = fmt ? String(fmt) : "json";
const threshold = isNaN(Number(thr)) ? undefined : Number(thr);
const preferLang = paramValid(prLang) && langCodes.has(prLang.toLowerCase()) ? prLang.toLowerCase() : undefined;

if(paramValid(q) || (paramValid(artist) && paramValid(song)))
{
const meta = await getMeta({
...(q ? {
q: String(q),
} : {
artist: String(artist),
song: String(song),
}),
threshold,
preferLang,
});
if(paramValid(q) || (paramValid(artist) && paramValid(song))) {
const meta = await getMeta({
...(q ? {
q: String(q),
} : {
artist: String(artist),
song: String(song),
}),
threshold,
preferLang,
});

if(!meta || meta.all.length < 1)
return respond(res, "clientError", "Found no results matching your search query", format, 0);
if(!meta || meta.all.length < 1)
return respond(res, "clientError", "Found no results matching your search query", format, 0);

// js2xmlparser needs special treatment when using arrays to produce a decent XML structure
const response = format !== "xml" ? meta : { ...meta, all: { "result": meta.all } };
// js2xmlparser needs special treatment when using arrays to produce a decent XML structure
const response = format !== "xml" ? meta : { ...meta, all: { "result": meta.all } };

return respond(res, "success", response, format, meta.all.length);
}
else
return respond(res, "clientError", "No search params (?q or ?song and ?artist) provided or they are invalid", req?.query?.format ? String(req.query.format) : undefined);
}
catch(err)
{
return respond(res, "serverError", `Encountered an internal server error: ${err instanceof Error ? err.message : ""}`, "json");
}
});
return respond(res, "success", response, format, meta.all.length);
}
else
return respond(res, "clientError", "No search params (?q or ?song and ?artist) provided or they are invalid", req?.query?.format ? String(req.query.format) : undefined);
}
catch(err) {
return respond(res, "serverError", `Encountered an internal server error: ${err instanceof Error ? err.message : ""}`, "json");
}
});

router.get("/search/top", async (req, res) => {
try
{
const { q, artist, song, format: fmt, threshold: thr, preferLang: prLang } = req.query;
router.get("/search/top", async (req, res) => {
try {
const { q, artist, song, format: fmt, threshold: thr, preferLang: prLang } = req.query;

const format: string = fmt ? String(fmt) : "json";
const threshold = isNaN(Number(thr)) ? undefined : Number(thr);
const preferLang = paramValid(prLang) && langCodes.has(prLang.toLowerCase()) ? prLang.toLowerCase() : undefined;
const format: string = fmt ? String(fmt) : "json";
const threshold = isNaN(Number(thr)) ? undefined : Number(thr);
const preferLang = paramValid(prLang) && langCodes.has(prLang.toLowerCase()) ? prLang.toLowerCase() : undefined;

if(paramValid(q) || (paramValid(artist) && paramValid(song)))
{
const meta = await getMeta({
...(q ? {
q: String(q),
} : {
artist: String(artist),
song: String(song),
}),
threshold,
preferLang,
});
if(paramValid(q) || (paramValid(artist) && paramValid(song))) {
const meta = await getMeta({
...(q ? {
q: String(q),
} : {
artist: String(artist),
song: String(song),
}),
threshold,
preferLang,
});

if(!meta || !meta.top)
return respond(res, "clientError", "Found no results matching your search query", format, 0);
if(!meta || !meta.top)
return respond(res, "clientError", "Found no results matching your search query", format, 0);

return respond(res, "success", meta.top, format, 1);
}
else
return respond(res, "clientError", "No search params (?q or ?song and ?artist) provided or they are invalid", req?.query?.format ? String(req.query.format) : undefined);
}
catch(err)
{
return respond(res, "serverError", `Encountered an internal server error${err instanceof Error ? err.message : ""}`, "json");
}
});
return respond(res, "success", meta.top, format, 1);
}
else
return respond(res, "clientError", "No search params (?q or ?song and ?artist) provided or they are invalid", req?.query?.format ? String(req.query.format) : undefined);
}
catch(err) {
return respond(res, "serverError", `Encountered an internal server error${err instanceof Error ? err.message : ""}`, "json");
}
});
}
44 changes: 21 additions & 23 deletions src/routes/translations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,34 +4,32 @@ import { getTranslations } from "../songData";
import { langCodes } from "../constants";

export function initTranslationsRoutes(router: Router) {
router.get("/translations", (req, res) => {
const format: string = req.query.format ? String(req.query.format) : "json";
router.get("/translations", (req, res) => {
const format: string = req.query.format ? String(req.query.format) : "json";

return respond(res, "clientError", "No song ID provided", format);
});
return respond(res, "clientError", "No song ID provided", format);
});

router.get("/translations/:songId", async (req, res) => {
try
{
const { songId } = req.params;
const { format: fmt, preferLang: prLang } = req.query;
router.get("/translations/:songId", async (req, res) => {
try {
const { songId } = req.params;
const { format: fmt, preferLang: prLang } = req.query;

const format: string = fmt ? String(fmt) : "json";
const preferLang = paramValid(prLang) && langCodes.has(prLang.toLowerCase()) ? prLang.toLowerCase() : undefined;
const format: string = fmt ? String(fmt) : "json";
const preferLang = paramValid(prLang) && langCodes.has(prLang.toLowerCase()) ? prLang.toLowerCase() : undefined;

if(!paramValid(songId) || isNaN(Number(songId)))
return respond(res, "clientError", "Provided song ID is invalid", format);
if(!paramValid(songId) || isNaN(Number(songId)))
return respond(res, "clientError", "Provided song ID is invalid", format);

const translations = await getTranslations(Number(songId), { preferLang });
const translations = await getTranslations(Number(songId), { preferLang });

if(!translations || translations.length === 0)
return respond(res, "clientError", "Couldn't find translations for this song", format, 0);
if(!translations || translations.length === 0)
return respond(res, "clientError", "Couldn't find translations for this song", format, 0);

return respond(res, "success", { translations }, format, translations.length);
}
catch(err)
{
return respond(res, "serverError", `Encountered an internal server error: ${err instanceof Error ? err.message : ""}`, "json");
}
});
return respond(res, "success", { translations }, format, translations.length);
}
catch(err) {
return respond(res, "serverError", `Encountered an internal server error: ${err instanceof Error ? err.message : ""}`, "json");
}
});
}
Loading

0 comments on commit 03dc9a7

Please sign in to comment.