headers.ts 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import parser from "yargs-parser"
  2. import { pipe, flow } from "fp-ts/function"
  3. import { HoppRESTHeader } from "@hoppscotch/data"
  4. import * as A from "fp-ts/Array"
  5. import * as S from "fp-ts/string"
  6. import * as O from "fp-ts/Option"
  7. import { tupleToRecord } from "~/helpers/functional/record"
  8. import {
  9. objHasProperty,
  10. objHasArrayProperty,
  11. } from "~/helpers/functional/object"
  12. const getHeaderPair = flow(
  13. S.split(": "),
  14. // must have a key and a value
  15. O.fromPredicate((arr) => arr.length === 2),
  16. O.map(([k, v]) => [k.trim(), v?.trim() ?? ""] as [string, string])
  17. )
  18. export function getHeaders(parsedArguments: parser.Arguments) {
  19. let headers: Record<string, string> = {}
  20. headers = pipe(
  21. parsedArguments,
  22. // make it an array if not already
  23. O.fromPredicate(objHasProperty("H", "string")),
  24. O.map((args) => [args.H]),
  25. O.alt(() =>
  26. pipe(
  27. parsedArguments,
  28. O.fromPredicate(objHasArrayProperty("H", "string")),
  29. O.map((args) => args.H)
  30. )
  31. ),
  32. O.map(
  33. flow(
  34. A.map(getHeaderPair),
  35. A.filterMap((a) => a),
  36. tupleToRecord
  37. )
  38. ),
  39. O.getOrElseW(() => ({}))
  40. )
  41. if (
  42. objHasProperty("A", "string")(parsedArguments) ||
  43. objHasProperty("user-agent", "string")(parsedArguments)
  44. )
  45. headers["User-Agent"] = parsedArguments.A ?? parsedArguments["user-agent"]
  46. const rawContentType =
  47. headers["Content-Type"] ?? headers["content-type"] ?? ""
  48. return {
  49. headers,
  50. rawContentType,
  51. }
  52. }
  53. export const recordToHoppHeaders = (
  54. headers: Record<string, string>
  55. ): HoppRESTHeader[] =>
  56. pipe(
  57. Object.keys(headers),
  58. A.map((key) => ({
  59. key,
  60. value: headers[key],
  61. active: true,
  62. })),
  63. A.filter(
  64. (header) =>
  65. header.key !== "Authorization" &&
  66. header.key !== "content-type" &&
  67. header.key !== "Content-Type"
  68. )
  69. )