R/rforcecom.create.R

Defines functions rforcecom.create

Documented in rforcecom.create

#' @export
rforcecom.create <- 
function(session, objectName, fields){

 # Create XML node set
 rforcecom.create.createXmlNodeSet <- function(nodelist){
  xmlNodeSet <- ""
  for(i in 1:length(nodelist)){
   if(!is.null(names(nodelist[i]))){
    if(!is.character(nodelist[i])){ nodelist[i] <- as.character(nodelist[i]) }
    nodeValue <- iconv(nodelist[i], from="", to="UTF-8")
    xmlNodeSet <- paste(xmlNodeSet, "<", names(nodelist[i]), ">", nodeValue ,"</", names(nodelist[i]), ">",sep="")
   }
  }
  return(xmlNodeSet)
 }
 
 # Create an XML
 xmlElem <- ""
 if(is.data.frame(fields)){
  xmlElem <- apply(fields, 2, rforcecom.create.createXmlNodeSet)
 } else {
  xmlElem <- rforcecom.create.createXmlNodeSet(fields)
 } 
 xmlBody <- paste("<?xml version=\"1.0\" encoding=\"UTF-8\"?><root>", xmlElem, "</root>", sep="")
 
 # Send records
 endpointPath <- rforcecom.api.getObjectEndpoint(session['apiVersion'], objectName)
 URL <- paste(session['instanceURL'], endpointPath, sep="")
 OAuthString <- paste("Bearer", session['sessionID'])
 httpHeader <- httr::add_headers("Authorization"=OAuthString, "Accept"="application/xml", 'Content-Type'="application/xml")
 res <- httr::POST(url=URL, config=httpHeader, body=xmlBody)
 res.content = httr::content(res, as='text', encoding='UTF-8')
 
 # BEGIN DEBUG
 if(exists("rforcecom.debug") && rforcecom.debug){ message(URL) }
 if(exists("rforcecom.debug") && rforcecom.debug){ message(xmlBody) }
 if(exists("rforcecom.debug") && rforcecom.debug){ message(res.content) }
 # END DEBUG
 
 # Parse XML
 x.root <- xmlRoot(xmlTreeParse(res.content, asText=T))
 
 # Check whether it success or not
 errorcode <- NA
 errormessage <- NA
 try(errorcode <- iconv(xmlValue(x.root[['Error']][['errorCode']]), from="UTF-8", to=""), TRUE)
 try(errormessage <- iconv(xmlValue(x.root[['Error']][['message']]), from="UTF-8", to=""), TRUE)
 if(!is.na(errorcode) && !is.na(errormessage)){
  stop(paste(errorcode, errormessage, sep=": "))
 }
 
 # Parse XML
 xdf <- xmlToDataFrame(getNodeSet(xmlParse(res.content),'//Result'))
 return(xdf)
}

Try the RForcecom package in your browser

Any scripts or data that you put into this service are public.

RForcecom documentation built on May 1, 2019, 6:31 p.m.