curl.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. export const CurlCodegen = {
  2. id: "curl",
  3. name: "cURL",
  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. headers,
  18. }) => {
  19. const requestString = []
  20. requestString.push(`curl -X ${method}`)
  21. requestString.push(` '${url}${pathName}?${queryString}'`)
  22. if (auth === "Basic Auth") {
  23. const basic = `${httpUser}:${httpPassword}`
  24. requestString.push(
  25. ` -H 'Authorization: Basic ${window.btoa(
  26. unescape(encodeURIComponent(basic))
  27. )}'`
  28. )
  29. } else if (auth === "Bearer Token" || auth === "OAuth 2.0") {
  30. requestString.push(` -H 'Authorization: Bearer ${bearerToken}'`)
  31. }
  32. if (headers) {
  33. headers.forEach(({ key, value }) => {
  34. if (key) requestString.push(` -H '${key}: ${value}'`)
  35. })
  36. }
  37. if (["POST", "PUT", "PATCH", "DELETE"].includes(method)) {
  38. let requestBody = rawInput ? rawParams : rawRequestBody
  39. requestBody = requestBody || ""
  40. requestString.push(` -d '${requestBody}'`)
  41. }
  42. return requestString.join(" \\\n")
  43. },
  44. }