template.js 1.41 KB
let images = require("./pics");


exports.askTemplate = (text) => {
  return {
    "attachment":{
      "type":"template",
      "payload":{
        "template_type":"button",
        "text": text,
        "buttons":[
          {
            "type":"postback",
            "title":"Cats",
            "payload":"CAT_PICS"
          },
          {
            "type":"postback",
            "title":"Dogs",
            "payload":"DOG_PICS"
          }
        ]
      }
    }
  }
}



exports.imageTemplate= (type, sender_id) => {
  return {
    "attachment":{
      "type":"image",
      "payload":{
        "url": getImage(type, sender_id),
        "is_reusable":true
      }
    }
  }
}

let users = {};

const getImage= (type, sender_id) => {
  // create user if doesn't exist
  if(users[sender_id] === undefined){
    users = Object.assign({
      [sender_id] : {
        'cats_count' : 0,
        'dogs_count' : 0
      }
    }, users);
  }

  let count = images[type].length, // total available images by type
      user = users[sender_id], // // user requesting image
      user_type_count = user[type+'_count'];


  // update user before returning image
  let updated_user = {
    [sender_id] : Object.assign(user, {
      [type+'_count'] : count === user_type_count + 1 ? 0 : user_type_count + 1
    })
  };
  // update users
  users = Object.assign(users, updated_user);

  console.log(users);
  return images[type][user_type_count];
}