Google Tasks API Node.js Example Code

Submitted by august on Thu, 08/09/2018 - 23:52
function getAuthClient() {
  var promises = [
    readFile('credentials.json').then(JSON.parse),
    readFile(TOKEN_PATH).then(JSON.parse)
  ];
  return Promise.all(promises).then((results) => {
    var credentials = results[0];
    var token = results[1];
    var client_secret = credentials.installed.client_secret;
    var client_id = credentials.installed.client_id;
    var redirect_uris = credentials.installed.redirect_uris;

    var oAuth2Client = new google.auth.OAuth2(client_id, client_secret, redirect_uris[0]);
    oAuth2Client.setCredentials(token);
    return oAuth2Client;
  }, function (err){
    console.error(err);
  })
}

function listTasklistsAsync(auth) {
  return new Promise(function (resolve, reject) {
    const service = google.tasks({version: 'v1', auth});
    service.tasklists.list({
      maxResults: 10,
    }, (err, res) => {
      if (err) {
        reject(err);
      } 
      else {
        resolve({'tasksLists': res.data.items, 'auth': auth});
      }
    });    
  })
}

function listTasks() {
  return getAuthClient().then(listTasklistsAsync).then(listTasksAsync).then((res) => res);
}


function updateTasks(params) {
  return getAuthClient().then((auth) => {
    params.auth = auth;
    return getTasksAsync(params)
  })
  .then((taskObj) => {
    params.taskObj = taskObj;
    params.taskObj.title = params.title;
    params.taskObj.notes = params.notes;
    return updateTasksAsync(params);
  })
  .then((res) => res)
  .catch((err) => {console.error(err)});
}

function updateTasksAsync(params) {
  var auth = params.auth;
  var task = params.task;
  var tasklist = params.tasklist;
  var taskObj = params.taskObj;
  return new Promise(function (resolve, reject) {
    const service = google.tasks({version: 'v1', auth});
    service.tasks.update({
      task: task,
      tasklist: tasklist,
      resource: taskObj
    }, (err, res) => {
      if (err) {
        reject(err);
      } 
      else {
        resolve(res.data);
      }
    });    
  })
}

 

Add new comment

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.