@dlog Restful JSON Controller


/ Published in: Other
Save to your folder(s)



Copy this code and paste it in your HTML
  1. public with sharing class RESTController {
  2. public void processRequest(){
  3. validateRequest();
  4. if( HasError )
  5. return;
  6.  
  7. //Add support for other types of verbs here
  8. processGetQuery();
  9. }
  10.  
  11. static final string ERROR_MISSING_SOQL_PARAM = 'Bad Request. Missing soql parameter';
  12. static final string ERROR_SOBJECT_MISSING = 'Bad Request. Could not parse SObject name from SOQL';
  13. static final string ERROR_FROM_MISSING = 'Bad request. SOQL missing FROM keyword';
  14. public void validateRequest(){
  15. if(Query == null){
  16. errorResponse(400, ERROR_MISSING_SOQL_PARAM);
  17. }
  18. else if(sObjectName == null){
  19. //Force a get of object name property.
  20. //Detailed error response should already be logged by sObjectName parser
  21. }
  22. }
  23.  
  24. public boolean HasError = False;
  25. private void errorResponse(integer errorCode, string errorMessage){
  26. JSONResponse.putOpt('status', new JSONObject.value(errorCode));
  27. JSONResponse.putOpt('error', new JSONObject.value(errorMessage));
  28. HasError = True;
  29. }
  30.  
  31. public void processGetQuery(){
  32. Map<String, Schema.SObjectField> fieldMap = Schema.getGlobalDescribe().get(SObjectName).getDescribe().fields.getMap();
  33. List<JSONObject.value> objectValues = new List<JSONObject.value>();
  34. List<sObject> resultList = Database.query(Query);
  35.  
  36. for(sObject obj : resultList){
  37. JSONObject json = new JSONObject();
  38. json.putOpt('id', new JSONObject.value( obj.Id ));
  39. for(SObjectField field : fieldMap.values() ){
  40. try{
  41. string f = field.getDescribe().getName();
  42. string v = String.valueOf( obj.get(field) );
  43. json.putOpt(f, new JSONObject.value( v ));
  44. }
  45. catch(Exception ex){
  46. //Ignore. Field not included in query
  47. }
  48. }
  49. objectValues.add(new JSONObject.value(json));
  50. }
  51. JSONResponse.putOpt('status', new JSONObject.value(200));
  52. JSONResponse.putOpt('records', new JSONObject.value(objectValues));
  53. }
  54.  
  55. private string m_query = null;
  56. public string Query{
  57. get{
  58. if(m_query == null && ApexPages.currentPage().getParameters().get('soql') != null){
  59. m_query = ApexPages.currentPage().getParameters().get('soql');
  60. }
  61. return m_query;
  62. }
  63. }
  64.  
  65. static final string SOQL_FROM_TOKEN = 'from ';
  66. private string m_sObject = null;
  67. public string sObjectName{
  68. get{
  69. if(m_sObject == null && Query != null){
  70. string soql = Query.toLowerCase();
  71.  
  72. integer sObjectStartToken = soql.indexOf(SOQL_FROM_TOKEN);
  73. if(sObjectStartToken == -1){
  74. errorResponse(400, ERROR_FROM_MISSING);
  75. return null;
  76. }
  77. sObjectStartToken += SOQL_FROM_TOKEN.length();
  78.  
  79. integer sObjectEndToken = soql.indexOf(' ', sObjectStartToken);
  80. if(sObjectEndToken == -1)
  81. sObjectEndToken = soql.length();
  82.  
  83. m_sObject = Query.substring(sObjectStartToken, sObjectEndToken);
  84. m_sObject = m_sObject.trim();
  85. system.debug('m_sObject = ' + m_sObject);
  86. }
  87. return m_sObject;
  88. }
  89. }
  90.  
  91. private JsonObject m_jsonResponse = null;
  92. public JSONObject JSONResponse{
  93. get{
  94. if(m_jsonResponse == null)
  95. m_jsonResponse = new JSONObject();
  96. return m_jsonResponse;
  97. }
  98. set{ m_jsonResponse = value;}
  99. }
  100.  
  101. public String getJSONResult() {
  102. return JSONResponse.valueToString();
  103. }
  104.  
  105. public static testMethod void unitTests(){
  106. RESTController controller = new RESTController();
  107. controller.processRequest();
  108. system.assertEquals(True, controller.HasError);
  109. system.assertEquals(True, controller.JSONResponse.has('status'));
  110. system.assertEquals(400, controller.JSONResponse.getValue('status').num);
  111. system.assertEquals(True, controller.JSONResponse.has('error'));
  112. system.assertEquals(ERROR_MISSING_SOQL_PARAM, controller.JSONResponse.getValue('error').str);
  113.  
  114. controller = new RESTController();
  115. ApexPages.currentPage().getParameters().put('soql', 'select Id fro Lead');
  116. controller.processRequest();
  117. system.assertEquals(True, controller.HasError);
  118. system.assertEquals(True, controller.JSONResponse.has('status'));
  119. system.assertEquals(400, controller.JSONResponse.getValue('status').num);
  120. system.assertEquals(ERROR_FROM_MISSING, controller.JSONResponse.getValue('error').str);
  121.  
  122. controller = new RESTController();
  123. ApexPages.currentPage().getParameters().put('soql', 'select Id from Lead');
  124. controller.processRequest();
  125. system.assertEquals(False, controller.HasError);
  126. system.assertEquals('Lead', controller.sObjectName);
  127.  
  128. Lead testLead = new Lead(FirstName = 'test', LastName = 'lead', Company='Bedrock', Email='[email protected]');
  129. insert testLead;
  130.  
  131. controller = new RESTController();
  132. ApexPages.currentPage().getParameters().put('soql', 'select Id from Lead where email=\'[email protected]\'');
  133. controller.processRequest();
  134. system.assertEquals(False, controller.HasError);
  135. system.assertEquals('Lead', controller.sObjectName);
  136. system.assertEquals(True, controller.JSONResponse.has('records'));
  137. }
  138. }
  139.  

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.