powershell-restmethod.js 1.8 KB

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