not really known
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

86 lines
2.5 KiB

  1. const googt = require('google-trends-api');
  2. const Promise = require('promise');
  3. const DAY = 1000 * 60 * 60 * 24; // 1 day in milliseconds
  4. const YEAR = DAY * 365; // 1 year in milliseconds
  5. const GEO = 'US'; //the scope of the trends
  6. /**
  7. desc: helper function for getYearStats, gets list of popularity for days in
  8. the month.
  9. */
  10. function getMonthStats(word, month){
  11. return new Promise(function(resolve, reject){
  12. //set up query for 1 month length
  13. googt.interestOverTime({
  14. keyword:word,
  15. startTime:new Date(Date.now() - (YEAR * month/12)),
  16. endTime:new Date(Date.now() - (YEAR * (month-1)/12))
  17. }).then(function(results){
  18. //parse the json, fill return array w tuples of date + value
  19. var times = JSON.parse(results).default.timelineData;
  20. var ret = [];
  21. for(var i = 0; i < times.length; ++i){
  22. var tup = new Object();
  23. tup.time = times[i].formattedTime;
  24. tup.value = times[i].value[0];
  25. ret[i] = tup;
  26. }
  27. resolve(ret);
  28. });
  29. });
  30. }
  31. module.exports=
  32. {
  33. /*
  34. desc: returns an integer score for the word over the day
  35. */
  36. getPopularity: function(word)
  37. {
  38. //must be a promise since call to trends API is async
  39. return new Promise(function(resolve, reject){
  40. //specifies the keyword, time interval, granularity, and region
  41. googt.interestOverTime({keyword:word,
  42. startTime:new Date(Date.now() - DAY),granularTimeResolution:true,
  43. geo:GEO
  44. })
  45. .then(function(results){
  46. //turn into json object
  47. data = JSON.parse(results).default.timelineData;
  48. //add up values
  49. var total = 0;
  50. data.forEach(function(element){
  51. total += element.value[0];
  52. })
  53. //tell function to return
  54. resolve(total);
  55. }).catch(function(err){
  56. reject("Google Trends Query Failed");
  57. });
  58. });
  59. },
  60. /**
  61. desc: returns a list of tuples (date, value) representing word's
  62. popularity for the past year
  63. */
  64. getYearStats: async function(word){
  65. var ret = [];
  66. for (var i = 9; i > 0; --i) {
  67. await getMonthStats(word,i).then(function(data){
  68. ret = ret.concat(data);
  69. });
  70. console.log(i);
  71. }
  72. return ret;
  73. }
  74. };