powershell-restmethod.js 1.9 KB

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