utils.ts 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. import { Response } from "express";
  2. import { Stringifiable } from "svcorelib";
  3. import jsonToXml from "js2xmlparser";
  4. import { ResponseType } from "./types";
  5. /** Checks if the value of a passed URL parameter is valid */
  6. export function paramValid(val: unknown): val is string {
  7. return typeof val === "string" && val.length > 0;
  8. }
  9. /**
  10. * Responds to an incoming request
  11. * @param type Type of response or status code
  12. * @param data The data to send in the response body
  13. * @param format json / xml
  14. */
  15. export function respond(res: Response, type: ResponseType | number, data: Stringifiable | Record<string, unknown>, format = "json", matchesAmt = 0)
  16. {
  17. let statusCode = 500;
  18. let error = true;
  19. let matches = null;
  20. let resData = {};
  21. if(typeof format !== "string" || !["json", "xml"].includes(format.toLowerCase()))
  22. format = "json";
  23. format = format.toLowerCase();
  24. switch(type)
  25. {
  26. case "success":
  27. error = false;
  28. matches = matchesAmt;
  29. statusCode = 200;
  30. resData = typeof data === "string" ? data : { ...data };
  31. break;
  32. case "clientError":
  33. error = true;
  34. matches = matchesAmt ?? null;
  35. statusCode = 400;
  36. resData = { message: data };
  37. break;
  38. case "serverError":
  39. error = true;
  40. matches = matchesAmt ?? null;
  41. statusCode = 500;
  42. resData = { message: data };
  43. break;
  44. default:
  45. if(typeof type === "number")
  46. {
  47. error = false;
  48. matches = matchesAmt ?? 0;
  49. statusCode = type;
  50. resData = typeof data === "string" ? data : { ...data };
  51. }
  52. break;
  53. }
  54. const mimeType = format !== "xml" ? "application/json" : "application/xml";
  55. resData = {
  56. error,
  57. matches,
  58. ...resData,
  59. timestamp: Date.now(),
  60. };
  61. const finalData = format === "xml" ? jsonToXml.parse("data", resData) : resData;
  62. res.setHeader("Content-Type", mimeType);
  63. res.status(statusCode)
  64. .send(finalData);
  65. }