method.ts 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import parser from "yargs-parser"
  2. import { pipe } from "fp-ts/function"
  3. import * as O from "fp-ts/Option"
  4. import * as R from "fp-ts/Refinement"
  5. import { getDefaultRESTRequest } from "~/newstore/RESTSession"
  6. import {
  7. objHasProperty,
  8. objHasArrayProperty,
  9. } from "~/helpers/functional/object"
  10. const defaultRESTReq = getDefaultRESTRequest()
  11. const getMethodFromXArg = (parsedArguments: parser.Arguments) =>
  12. pipe(
  13. parsedArguments,
  14. O.fromPredicate(objHasProperty("X", "string")),
  15. O.map((args) => args.X.trim()),
  16. O.chain((xarg) =>
  17. pipe(
  18. O.fromNullable(
  19. xarg.match(/GET|POST|PUT|PATCH|DELETE|HEAD|CONNECT|OPTIONS|TRACE/i)
  20. ),
  21. O.alt(() => O.fromNullable(xarg.match(/[a-zA-Z]+/)))
  22. )
  23. ),
  24. O.map((method) => method[0])
  25. )
  26. const getMethodByDeduction = (parsedArguments: parser.Arguments) => {
  27. if (
  28. pipe(
  29. objHasProperty("T", "string"),
  30. R.or(objHasProperty("upload-file", "string"))
  31. )(parsedArguments)
  32. )
  33. return O.some("put")
  34. else if (
  35. pipe(
  36. objHasProperty("I", "boolean"),
  37. R.or(objHasProperty("head", "boolean"))
  38. )(parsedArguments)
  39. )
  40. return O.some("head")
  41. else if (objHasProperty("G", "boolean")(parsedArguments)) return O.some("get")
  42. else if (
  43. pipe(
  44. objHasProperty("d", "string"),
  45. R.or(objHasArrayProperty("d", "string")),
  46. R.or(objHasProperty("F", "string")),
  47. R.or(objHasArrayProperty("F", "string"))
  48. )(parsedArguments)
  49. )
  50. return O.some("POST")
  51. else return O.none
  52. }
  53. /**
  54. * Get method type from X argument in curl string or
  55. * find it out through other arguments
  56. * @param parsedArguments Parsed Arguments object
  57. * @returns Method string
  58. */
  59. export const getMethod = (parsedArguments: parser.Arguments): string =>
  60. pipe(
  61. getMethodFromXArg(parsedArguments),
  62. O.alt(() => getMethodByDeduction(parsedArguments)),
  63. O.getOrElse(() => defaultRESTReq.method)
  64. )