translations.ts 1.4 KB

123456789101112131415161718192021222324252627282930313233343536
  1. import { Router } from "express";
  2. import { paramValid, respond } from "../utils";
  3. import { getTranslations } from "../songData";
  4. export function initTranslationsRoutes(router: Router) {
  5. router.get("/translations", (req, res) => {
  6. const format: string = req.query.format ? String(req.query.format) : "json";
  7. return respond(res, "clientError", "No song ID provided", format);
  8. });
  9. router.get("/translations/:songId", async (req, res) => {
  10. const { format: fmt } = req.query;
  11. const format: string = fmt ? String(fmt) : "json";
  12. try {
  13. const { songId } = req.params;
  14. if(!paramValid(songId) || isNaN(Number(songId)))
  15. return respond(res, "clientError", "Provided song ID is invalid", format);
  16. const translations = await getTranslations(Number(songId));
  17. if(translations === null || (Array.isArray(translations) && translations.length === 0))
  18. return respond(res, "clientError", "Couldn't find translations for this song", format, 0);
  19. if(translations === undefined)
  20. return respond(res, "clientError", "Couldn't find a song with the provided ID", format, 0);
  21. return respond(res, "success", { translations }, format, translations.length);
  22. }
  23. catch(err) {
  24. return respond(res, "serverError", `Encountered an internal server error: ${err instanceof Error ? err.message : ""}`, format);
  25. }
  26. });
  27. }