utils.ts 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. import { Response } from "express";
  2. import { Stringifiable, byteLength } from "svcorelib";
  3. import { parse as jsonToXml } from "js2xmlparser";
  4. import { ResponseType } from "./types";
  5. /** Checks if the value of a passed URL parameter is a string with length > 0 */
  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?: number)
  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 = 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 = data;
  51. }
  52. break;
  53. }
  54. resData = {
  55. error,
  56. ...(matches === undefined ? {} : { matches }),
  57. ...resData,
  58. };
  59. const finalData = format === "xml" ? jsonToXml("data", resData) : resData;
  60. const contentLen = byteLength(typeof finalData === "string" ? finalData : JSON.stringify(finalData));
  61. res.setHeader("Content-Type", format === "xml" ? "application/xml" : "application/json");
  62. contentLen > -1 && res.setHeader("Content-Length", contentLen);
  63. res.status(statusCode).send(finalData);
  64. }