Google Classroom Batching

32 views
Skip to first unread message

Clay Smith

unread,
Mar 7, 2020, 10:26:41 AM3/7/20
to Google Apps Script Community
Hi All, I'm attempting to "create" students to a classroom with a batch request. I get returned "Not found" as the error. Has anyone been able to make this work?
Thanks, 
Clay


//emails is an array of email. courseid is the classroom id

function(emails, courseid){
  for(var i=0;i<emails.length;i++){
    var studentResource = {
                userId: emails[i]
            }
    var classResource = {
      method: 'POST',
      requestBody: studentResource
    }
    body.push(classResource)
  }
  var response=  batch(body,"https://www.googleapis.com/batch/classroom/v1");
}


//batch function with exp backoff
function batch(body, url) {
  if(body.length<1){
    return []
  }
  var boundary = 'xxxxxxxxxx';
  var contentId = 0;
  var data = '--' + boundary + '\r\n';
  for (var i in body) {
    data += 'Content-Type: application/http\r\n';
    data += 'Content-ID: ' + ++contentId + '\r\n\r\n';
    data += body[i].method + ' ' + body[i].endpoint + '\r\n';
    data += body[i].requestBody ? 'Content-Type: application/json; charset=utf-8\r\n\r\n' : '\r\n';
    data += body[i].requestBody ? JSON.stringify(body[i].requestBody) + '\r\n' : '';
    data += "--" + boundary + '\r\n';
  }
  var payload1 = Utilities.newBlob(data).getBytes();
  var oAuth = ScriptApp.getOAuthToken();
  var options = {
    method: 'POST',
    contentType: 'multipart/mixed; boundary=' + boundary,
    payload: payload1,
    headers: {Authorization: 'Bearer ' + oAuth},
    muteHttpExceptions: true
  };
  var complete=false;
  for (var n=0; n<=backoff; n++) {
    if(complete){
      break;
    }
    console.log('backoff',n);
    var response =UrlFetchApp.fetch(url, options).getContentText();
    response =responseJSON(response);
    if(typeof response=='object'){
      for(var r=0;r<response.length;r++){
        if(response[r].error || response[r].errors){
          var errors = response[r].error?response[r].error:response[r].errors
          if(errors.errors){
            for(var u =0;u<errors.errors.length;u++){
              console.log('reason:',errors.errors[u].reason)
              if(errors.errors[u].reason=='duplicate'){
                var complete=true;
                break;
              }
            }
          }
          console.log('ERROR:',errors)
          Utilities.sleep((Math.pow(2,n)*1000) + (Math.round(Math.random() * 1000)));
          break
        }else{
          var complete=true;
          break;
        }
      }
    }else{
      console.log('else',typeof response)
    }
  }
  return response
}


Reply all
Reply to author
Forward
0 new messages