• Nihon Taisai
  • NEWBIE
  • 30 Points
  • Member since 2018

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 9
    Questions
  • 1
    Replies
Is there any way to make this code better? I need to get here msgs from HttpPost custom method: Success adding or Error msg. HttpPost method has this functions, but I don't know how to make the 'dialogue' between 2 orgs easier. Maybe I need some try-catches here too? To send messages to the other side if something is wrong.
public class Token{
    public String accessToken{get;set;}    
}

public static void postCallout() {
    //test record:
    Type__c typ = [SELECT Id, Name FROM Type__c WHERE Name = 'ttt'];
    Http ourHttp = new Http();
    //Here are my consumer key, consumer secret, username, password and request:
    String requestBody = getAccess();  
    HttpRequest req = new HttpRequest();
    req.setBody(requestBody);
    req.setMethod('POST');
    req.setEndpoint('https://p21.lightning.force.com/services/oauth2/token'); 
    HttpResponse response = ourHttp.send(req);      
    Token authentication = (Token)JSON.deserialize(response.getbody(), Token.class);

    if(objAuthenticationInfo.accessToken != null){
        HttpRequest req2 = new HttpRequest();
        req2.setHeader('Authorization','Bearer ' + authentication.accessToken);
        req2.setHeader('Content-Type','application/json');
        req2.setHeader('accept','application/json');
        req2.setMethod('POST');
        req2.setEndpoint('https://p21.lightning.force.com/services/apexrest/types/');
        req2.setBody(GenerateJSON(typ));
        response = ourHttp.send(req2);
    }
}

 
We have an example from trailhead. But how can we change Id =: recordId to the External_id =: recordId in SOQL? I think we also change the logic of our code, because if just change it - Http-service doesn't work (List is always null). Code:
@HttpDelete
    global static void deleteCase() {
        RestRequest request = RestContext.request;
        String caseId = request.requestURI.substring(
            request.requestURI.lastIndexOf('/')+1);
        Case thisCase = [SELECT Id FROM Case WHERE Id = :caseId];
        delete thisCase;
    }
Test:
@isTest static void testDeleteCase() {
        Id recordId = createTestRecord();
        // Set up a test request
        RestRequest request = new RestRequest();
        request.requestUri =
            'https://yourInstance.salesforce.com/services/apexrest/Cases/'
            + recordId;
        request.httpMethod = 'GET';
        RestContext.request = request;
        // Call the method to test
        CaseManager.deleteCase();
        // Verify record is deleted
        List<Case> cases = [SELECT Id FROM Case WHERE Id=:recordId];
        System.assert(cases.size() == 0);
    }

// Helper method
    static Id createTestRecord() {
        // Create test record
        Case caseTest = new Case(
            Subject='Test record',
            Status='New',
            Origin='Phone',
            Priority='Medium');
        insert caseTest;
        return caseTest.Id;
    }
I need to update a right record with ExternalID = Id of inserted record. And I try to check this field (ExternalID) in SOQL, but get an error System.QueryException: List has no rows for assignment to SObject. What is wrong here?
@HttpPatch
global static void upd() {
    RestRequest req = RestContext.request;
    String thisID = req.params.get('Id');
    Product__c product = [SELECT Id FROM Product__c WHERE ExternalID__c =: thisID];
    Map<String, Object> params = (Map<String, Object>)JSON.deserializeUntyped(req.requestbody.tostring());
    for(String fieldName : params.keySet()) {
        product.put(fieldName, params.get(fieldName));
    }
    update product;
}
Test (coverage 100%, but error):
@isTest
static void testupd() {
    Product__c test = new Product__c(Name__c = 'Orange');
    insert test;
    RestRequest req = new RestRequest();
    req.requestUri = System.URL.getSalesforceBaseUrl().toExternalForm() +
                     '/services/apexrest/Product__c/ExternalID__c/'
                     + test.Id;
    //even this can't help to put id of inserted test-product into ExternalID__c:
    req.params.put('ExternalID__c', test.Id);
    req.httpMethod = 'PATCH';
    req.addHeader('Content-Type', 'application/json');
    req.requestBody = Blob.valueOf('{"Name__c": "Cherry"}'); 
    RestContext.request = req;
    //update method:
    TheClass.upd();
    //Error is here:
    Product__c updatedRecord = [SELECT Name__c
                                FROM Product__c
                                WHERE ExternalID__c =: test.Id];
    System.assert(updatedRecord.Name__c == 'Cherry');
}

 
I have this error because I duplicate my object by method's calling. How can I fix it?

My HttpPost:
public static Avia__c ParseRequest(RestRequest req) {
    Avia__c a = new Avia__c();
    String body = req.requestBody.toString();
    a = (Avia__c)JSON.deserialize(body, Avia__c.class);
    return a;
}
@HttpPost
global static Id doPost() {
    RestRequest req = RestContext.request;
    Avia__c a = ParseRequest(req);
    insert a;
    return a.id;
}
My test:
@isTest
static void testPost() { 
    Avia__c testRecord = new Avia__c (Name = 'Name');
    String json = System.JSON.serialize(testRecord);
    RestRequest request = new RestRequest();
    request.requestBody = Blob.valueOf(json);
    request.httpMethod = 'POST';
    request.addHeader('Content-Type', 'application/json');
    request.requestUri = System.URL.getSalesforceBaseUrl().toExternalForm() + '/services/apexrest/Job_Advertisement__c/' + testRecord.Id;
    RestContext.request = request;
    Avia__c ourRecord = Endpoint.ParseRequest(request);
    System.assertEquals(testRecord, ourRecord);

    Id tId = Endpoint.doPost();  //here is an error
    System.assertEquals(testRecord.Id, tId);
}
I just call the method and it inserts a record twice. So I become Id's conflict. How can I change it? Of caurse I can upsert it, but I also have a PUT method, so I don't need it in my POST.
When we post a Box record we also send Id from another record (callout side) in External Id for Box record. How can we write this request in HttpPost code? Or we don't need it in HttpPost?

My code:
@HttpPost
    global static Box__c postBox(String title){
        RestRequest req = RestContext.request;
                                                                
        Box__c b = new Box__c(
            Title__c = title,
            );
        insert b;
        return b;
    }

 

How can I test this for 100% coverage?
@HttpGet
global static List<Box__c> getBox(){
    RestRequest req = RestContext.request;
    String boxId = req.params.get('Id');
    if(boxId == null)
    {
        return [SELECT Id, Title__c
                FROM Box__c
                LIMIT 1000];
    }
    else
    {
        List<Box__c> boxList;
        boxList = [SELECT Id, Title__c 
                   FROM Box__c
                   WHERE Id =: boxId
                   LIMIT 1000];
        return boxList;
    }
}
My test It works, but only 80%:
@isTest
static void testBox() {
    Id recordId = idd();
    RestRequest request = new RestRequest();
    request.requestUri = System.URL.getSalesforceBaseUrl().toExternalForm() + '/services/apexrest/Box__c/' + recordId;            
    request.httpMethod = 'GET';
    RestContext.request = request;

    List<Box__c> b = OurClass.getBox();

    for(Box__c pneBox : b){
        System.assertEquals(pneBox.Id, recordId);
    }
}

static Id idd() {
    Box__c bb = new Box__c(
        Title__c = 'Title',
    );
    insert bb;
    return bb.Id;
}
0down votefavorite
I need to make integration between Org1 and Org2. We created a callout POST. When we create an object in Org1, we also create an object in Org2. POST work. All is Ok. Now I need also delete an object in Org2, if External Id in this obj == Id in obj from Org1.
Something like that:
If(org2Object.ExternalId == org1Object.Id){
   Delete org2Object;
}

I try to delete a record from another org, but I don't know, how to write it right. My Delete callout:
private static Position__c pos = [SELECT Id, Name, Location__c, Job_Description__c, Salary_Range__c, Skills_Required__c, Education__c,
                       Hiring_Manager__r.Name, Email__c, Phone__c, Status__c
                       FROM Position__c WHERE Name = 'Title22'];

public static String getRequestBody(){
    Settings__c settings = [SELECT ConsumerKey__c, ClientSecret__c, Username__c, Password__c, SecurityToken__c
                            FROM Settings__c
                            WHERE Name = 'OurSettings'];  
    String consumerKey = settings.ConsumerKey__c;
    String consumerSecret = settings.ClientSecret__c;
    String username = settings.Username__c;
    String password = settings.Password__c + settings.SecurityToken__c;
    String request = 'grant_type=password&client_id=' + consumerKey +'&client_secret=' + consumerSecret +
                     '&username=' + username + '&password='+password;
    return request;
}


public static void deleteCalloutResponseContents(Id ourId){
    Http ourHttp = new Http();
    HttpRequest request = httpRequest('DELETE');
    HttpResponse response = ourHttp.send(request);
    OAuth2 objAuthenticationInfo = (OAuth2)JSON.deserialize(response.getbody(), OAuth2.class);

    if(objAuthenticationInfo.ACCESS_TOKEN != null){
        pos.Id = ourId;

        HttpRequest finalRequest = new HttpRequest();
        String jsonstr='{"Position_ID__c":"'+ ourId +'"}';

        finalRequest.setHeader('Authorization','Bearer '+ objAuthenticationInfo.ACCESS_TOKEN);
        finalRequest.setHeader('Content-Type','application/json');
        finalRequest.setHeader('accept','application/json');
        finalRequest.setBody(jsonstr);
        finalRequest.setMethod('DELETE');

        request.setEndpoint(System.Label.Job_Advertisement_URL + '/services/data/v43.0/sobjects/Job_Advertisement__c/ourId');
        response = ourHttp.send(finalRequest);
        System.debug('RESPONSE BODY: ' + response.getBody());
    }        
}

public class OAuth2{
        public String ACCESS_TOKEN{get;set;}    
    }

How can I fix it?
Hello. I'm trainee now. I have a mentor now. But when I ask him for help he aswers 'Just google it' :( So I can't understand some things and can't solve  some tasks. I don't ask for free help. I can pay. I Just need understand all what I want. Thank you.
All my values transferred good, but it's just Strings. When I try to post Picklist value into Text field I get this in debug msg: [{"message":"Unexpected parameter encountered during deserialization: location at [line:9, column:17]","errorCode":"JSON_PARSER_ERROR"}]
I need to update a right record with ExternalID = Id of inserted record. And I try to check this field (ExternalID) in SOQL, but get an error System.QueryException: List has no rows for assignment to SObject. What is wrong here?
@HttpPatch
global static void upd() {
    RestRequest req = RestContext.request;
    String thisID = req.params.get('Id');
    Product__c product = [SELECT Id FROM Product__c WHERE ExternalID__c =: thisID];
    Map<String, Object> params = (Map<String, Object>)JSON.deserializeUntyped(req.requestbody.tostring());
    for(String fieldName : params.keySet()) {
        product.put(fieldName, params.get(fieldName));
    }
    update product;
}
Test (coverage 100%, but error):
@isTest
static void testupd() {
    Product__c test = new Product__c(Name__c = 'Orange');
    insert test;
    RestRequest req = new RestRequest();
    req.requestUri = System.URL.getSalesforceBaseUrl().toExternalForm() +
                     '/services/apexrest/Product__c/ExternalID__c/'
                     + test.Id;
    //even this can't help to put id of inserted test-product into ExternalID__c:
    req.params.put('ExternalID__c', test.Id);
    req.httpMethod = 'PATCH';
    req.addHeader('Content-Type', 'application/json');
    req.requestBody = Blob.valueOf('{"Name__c": "Cherry"}'); 
    RestContext.request = req;
    //update method:
    TheClass.upd();
    //Error is here:
    Product__c updatedRecord = [SELECT Name__c
                                FROM Product__c
                                WHERE ExternalID__c =: test.Id];
    System.assert(updatedRecord.Name__c == 'Cherry');
}