salesforce-apex.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. export const SalesforceApexCodegen = {
  2. id: "salesforce-apex",
  3. name: "Salesforce Apex",
  4. language: "apex",
  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. // initial request setup
  22. let requestBody = rawInput ? rawParams : rawRequestBody
  23. requestBody = JSON.stringify(requestBody)
  24. .replace(/^"|"$/g, "")
  25. .replace(/\\"/g, '"')
  26. .replace(/'/g, "\\'") // Apex uses single quotes for strings
  27. // create request
  28. requestString.push(`HttpRequest request = new HttpRequest();\n`)
  29. requestString.push(`request.setMethod('${method}');\n`)
  30. requestString.push(
  31. `request.setEndpoint('${url}${pathName}?${queryString}');\n\n`
  32. )
  33. // authentification
  34. if (auth === "Basic Auth") {
  35. const basic = `${httpUser}:${httpPassword}`
  36. requestString.push(
  37. `request.setHeader('Authorization', 'Basic ${window.btoa(
  38. unescape(encodeURIComponent(basic))
  39. )}');\n`
  40. )
  41. } else if (auth === "Bearer Token" || auth === "OAuth 2.0") {
  42. requestString.push(
  43. `request.setHeader('Authorization', 'Bearer ${bearerToken}');\n`
  44. )
  45. }
  46. // content type
  47. if (contentType) {
  48. requestString.push(
  49. `request.setHeader('Content-Type', '${contentType}');\n`
  50. )
  51. }
  52. // custom headers
  53. if (headers) {
  54. headers.forEach(({ key, value }) => {
  55. if (key) {
  56. requestString.push(`request.setHeader('${key}', '${value}');\n`)
  57. }
  58. })
  59. }
  60. requestString.push(`\n`)
  61. // set body
  62. if (["POST", "PUT", "PATCH", "DELETE"].includes(method)) {
  63. requestString.push(`request.setBody('${requestBody}');\n\n`)
  64. }
  65. // process
  66. requestString.push(`try {\n`)
  67. requestString.push(` Http client = new Http();\n`)
  68. requestString.push(` HttpResponse response = client.send(request);\n`)
  69. requestString.push(` System.debug(response.getBody());\n`)
  70. requestString.push(`} catch (CalloutException ex) {\n`)
  71. requestString.push(
  72. ` System.debug('An error occurred ' + ex.getMessage());\n`
  73. )
  74. requestString.push(`}`)
  75. return requestString.join("")
  76. },
  77. }