shell-httpie.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. export const ShellHttpieCodegen = {
  2. id: "shell-httpie",
  3. name: "Shell HTTPie",
  4. language: "sh",
  5. generator: ({
  6. url,
  7. pathName,
  8. queryString,
  9. auth,
  10. httpUser,
  11. httpPassword,
  12. bearerToken,
  13. method,
  14. rawInput,
  15. rawParams,
  16. rawRequestBody,
  17. contentType,
  18. headers,
  19. }) => {
  20. const methodsWithBody = ["POST", "PUT", "PATCH", "DELETE"]
  21. const includeBody = methodsWithBody.includes(method)
  22. const requestString = []
  23. let requestBody = rawInput ? rawParams : rawRequestBody
  24. requestBody = requestBody.replace(/'/g, "\\'")
  25. if (requestBody.length !== 0 && includeBody) {
  26. // Send request body via redirected input
  27. requestString.push(`echo -n $'${requestBody}' | `)
  28. }
  29. // Executable itself
  30. requestString.push(`http`)
  31. // basic authentication
  32. if (auth === "Basic Auth") {
  33. requestString.push(` -a ${httpUser}:${httpPassword}`)
  34. }
  35. // URL
  36. let escapedUrl = `${url}${pathName}?${queryString}`
  37. escapedUrl = escapedUrl.replace(/'/g, "\\'")
  38. requestString.push(` ${method} $'${escapedUrl}'`)
  39. // All headers
  40. if (contentType) {
  41. requestString.push(` 'Content-Type:${contentType}; charset=utf-8'`)
  42. }
  43. if (headers) {
  44. headers.forEach(({ key, value }) => {
  45. requestString.push(
  46. ` $'${key.replace(/'/g, "\\'")}:${value.replace(/'/g, "\\'")}'`
  47. )
  48. })
  49. }
  50. if (auth === "Bearer Token" || auth === "OAuth 2.0") {
  51. requestString.push(` 'Authorization:Bearer ${bearerToken}'`)
  52. }
  53. return requestString.join("")
  54. },
  55. }