powershell-restmethod.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. export const PowershellRestmethodCodegen = {
  2. id: "powershell-restmethod",
  3. name: "PowerShell RestMethod",
  4. language: "powershell",
  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. headers,
  18. }) => {
  19. const methodsWithBody = ["Put", "Post", "Delete"]
  20. const formattedMethod =
  21. method[0].toUpperCase() + method.substring(1).toLowerCase()
  22. const includeBody = methodsWithBody.includes(formattedMethod)
  23. const requestString = []
  24. let genHeaders = []
  25. let variables = ""
  26. requestString.push(
  27. `Invoke-RestMethod -Method '${formattedMethod}' -Uri '${url}${pathName}?${queryString}'`
  28. )
  29. const requestBody = rawInput ? rawParams : rawRequestBody
  30. if (["POST", "PUT", "PATCH", "DELETE"].includes(method)) {
  31. if (requestBody && includeBody) {
  32. variables = variables.concat(`$body = @'\n${requestBody}\n'@\n\n`)
  33. }
  34. }
  35. if (headers) {
  36. headers.forEach(({ key, value }) => {
  37. if (key) genHeaders.push(` '${key}' = '${value}'\n`)
  38. })
  39. }
  40. if (auth === "Basic Auth") {
  41. const basic = `${httpUser}:${httpPassword}`
  42. genHeaders.push(
  43. ` 'Authorization' = 'Basic ${window.btoa(
  44. unescape(encodeURIComponent(basic))
  45. )}'\n`
  46. )
  47. } else if (auth === "Bearer Token" || auth === "OAuth 2.0") {
  48. genHeaders.push(` 'Authorization' = 'Bearer ${bearerToken}'\n`)
  49. }
  50. genHeaders = genHeaders.join("").slice(0, -1)
  51. if (genHeaders) {
  52. variables = variables.concat(`$headers = @{\n${genHeaders}\n}\n`)
  53. requestString.push(` -Headers $headers`)
  54. }
  55. if (requestBody && includeBody) {
  56. requestString.push(` -Body $body`)
  57. }
  58. return `${variables}${requestString.join("")}`
  59. },
  60. }