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