salesforce-apex.js 2.2 KB

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