curl.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. export const CurlCodegen = {
  2. id: "curl",
  3. name: "cURL",
  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 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(unescape(encodeURIComponent(basic)))}'`
  26. )
  27. } else if (auth === "Bearer Token" || auth === "OAuth 2.0") {
  28. requestString.push(` -H 'Authorization: Bearer ${bearerToken}'`)
  29. }
  30. if (headers) {
  31. headers.forEach(({ key, value }) => {
  32. if (key) requestString.push(` -H '${key}: ${value}'`)
  33. })
  34. }
  35. if (["POST", "PUT", "PATCH", "DELETE"].includes(method)) {
  36. const requestBody = rawInput ? rawParams : rawRequestBody
  37. requestString.push(` -H 'Content-Type: ${contentType}; charset=utf-8'`)
  38. requestString.push(` -d '${requestBody}'`)
  39. }
  40. return requestString.join(" \\\n")
  41. },
  42. }