I have a scenario where the external party might send three different types of payloads: TypeA, TypeB, TypeC. for TypeA I will match and update 20 Account fields, for TypeB = 10 fiels, for TypeC = 5fiels. Using Json2Apex, now I have 3 classes for each Type and a restresource class where I will need to check if the incoming payload is typeA, typeB, or TypeC to make the correct mappings and updates. ** all the payloads have the parameter called 'Type' where it indicates the Type. I have an example code, I want to know if there is a better way to build and implement this scenario. thank you.
@RestResource(urlMapping='/urlMapping')
global without sharing class TSTscriptForwebService {
global class ResponseClass {
public boolean success;
public string message;
public ResponseClass(boolean success, string message){
this.success = success;
this.message = message;
}
}
@httpPost
global static ResponseClass postCalls(){
String requestBody ;
try {
requestBody = RestContext.request.requestBody.toString();
typeA payloadA = typeA.parse(requestBody);
if(payloadA.type == 'A') {
/*
SOQL
name = payloadA.Name
age = payloadA.age
etc... update;
*/
} else if(payloadA.type == 'B') {
typeB payloadB = typeB.parse(requestBody);
/*
SOQL
name = payloadB.Name
age = payloadB.age
etc... update;
*/
} else /*typeC*/ {
typeC payloadC = typeC.parse(requestBody);
/*
SOQL
name = payloadC.Name
age = payloadC.age
etc... update;
*/
}
} catch(Exception e) {
ResponseClass resp = new ResponseClass(false, e.getMessage());
return resp;
}
return new ResponseClass(true, '');
}
}