mutators.ts 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. import fs from "fs/promises";
  2. import { FormDataEntry } from "../types/request";
  3. import { error } from "../types/errors";
  4. import { isRESTCollection, isHoppErrnoException } from "./checks";
  5. import { HoppCollection } from "@hoppscotch/data";
  6. /**
  7. * Parses array of FormDataEntry to FormData.
  8. * @param values Array of FormDataEntry.
  9. * @returns FormData with key-value pair from FormDataEntry.
  10. */
  11. export const toFormData = (values: FormDataEntry[]) => {
  12. const formData = new FormData();
  13. values.forEach(({ key, value }) => formData.append(key, value));
  14. return formData;
  15. };
  16. /**
  17. * Parses provided error message to maintain hopp-error messages.
  18. * @param e Custom error data.
  19. * @returns Parsed error message without extra spaces.
  20. */
  21. export const parseErrorMessage = (e: unknown) => {
  22. let msg: string;
  23. if (isHoppErrnoException(e)) {
  24. msg = e.message.replace(e.code! + ":", "").replace("error:", "");
  25. } else if (typeof e === "string") {
  26. msg = e;
  27. } else {
  28. msg = JSON.stringify(e);
  29. }
  30. return msg.replace(/\n+$|\s{2,}/g, "").trim();
  31. };
  32. export async function readJsonFile(path: string): Promise<unknown> {
  33. if (!path.endsWith(".json")) {
  34. throw error({ code: "INVALID_FILE_TYPE", data: path });
  35. }
  36. try {
  37. await fs.access(path);
  38. } catch (e) {
  39. throw error({ code: "FILE_NOT_FOUND", path: path });
  40. }
  41. try {
  42. return JSON.parse((await fs.readFile(path)).toString());
  43. } catch (e) {
  44. throw error({ code: "UNKNOWN_ERROR", data: e });
  45. }
  46. }
  47. /**
  48. * Parses collection json file for given path:context.path, and validates
  49. * the parsed collectiona array.
  50. * @param path Collection json file path.
  51. * @returns For successful parsing we get array of HoppCollection,
  52. */
  53. export async function parseCollectionData(
  54. path: string
  55. ): Promise<HoppCollection[]> {
  56. let contents = await readJsonFile(path);
  57. const maybeArrayOfCollections: unknown[] = Array.isArray(contents)
  58. ? contents
  59. : [contents];
  60. if (maybeArrayOfCollections.some((x) => !isRESTCollection(x))) {
  61. throw error({
  62. code: "MALFORMED_COLLECTION",
  63. path,
  64. data: "Please check the collection data.",
  65. });
  66. }
  67. return maybeArrayOfCollections as HoppCollection[];
  68. }