Nodejs callback function in http request - javascript

I get the error that function is not found.
I don't get it.. is it because of the callback in the https.get?
I want to call the callback function when the http request is done.
const happy = ['happy'];
twitterService.twitter(happy, '1233,1233', '50', function (length) {
console.log(length + " bepedie boopdap");
});
twitter.js
module.exports.twitter = function (hashtags, location, distance, callbackLength) {
if (hashtags.length !== 0) {
let hashURL = createHashtagUrl(hashtags);
const options = {
host: config.apiURL,
path: '/1.1/search/tweets.json?q=' + hashURL + '&geocode=' + location + ',' + distance + 'km&count=100',
method: 'GET',
headers: {
'Authorization': 'Bearer ' + config.base64Token
}
};
https.get(options, function (res) {
let body = '';
res.on('data', function (data) {
body += data;
});
res.on('end', function () {
let jsonObj = JSON.parse(body);
let length = jsonObj.statuses.length;
callbackLength(length); // HERE its says .. is not a function
})
.on('error', function (e) {
console.log("ERROR BEEP BEEP" + e);
});
});
}
};
function createHashtagUrl(hashtags) {
let hashURL = config.hashtagUnicode + hashtags[0];
for (let i = 1; i < hashtags.length; i++)
hashURL += '+OR+' + config.hashtagUnicode + hashtags[i];
return hashURL;
}
anyone an idea?

Not sure, but maybe need to change request part.
var req = https.get(options, function (res) {
let body = '';
res.on('data', function (data) {
body += data;
});
});
req.on('end', function () {
let jsonObj = JSON.parse(body);
let length = jsonObj.statuses.length;
callbackLength(length);
})
.on('error', function (e) {
console.log("ERROR BEEP BEEP" + e);
});`enter code here`

Related

TypeError: Cannot find function forEach in object in Google App Script

I keep running to Cannot find function for each in object error while trying to loop entries. Is there something I am not seeing?. Here the code. This code is supposed to fetch time data from a system via API do calculations and send email
function getTime() {
var range = [5323, 9626, 4998];
var user = [];
for (var i = 0; i < range.length; i++) {
var auth = 'token'
var from = '2020-01-08'
var to = '2020-01-09'
var url = 'https://api.10000ft.com/api/v1/users/' + range[i] + '/time_entries?from=' + from + '&to=' + to + '&auth=' + auth;
var options = {
method: 'get',
headers: {
Authorization: 'Bearer ' + auth
}
};
var submitted_time_entries = {};
var response = UrlFetchApp.fetch(url, options);
var response = JSON.parse(response.getContentText());
var time_entries = response.data;
time_entries.forEach(function (time_entry) {
if (time_entry.user_id in submitted_time_entries) {
submitted_time_entries[time_entry.user_id] += time_entry.hours;
} else {
submitted_time_entries[time_entry.user_id] = time_entry.hours;
}
});
submitted_time_entries.forEach(function (user_id) {
if (submitted_time_entries[user_id] < 3) {
//send mail
}
});
}
}
response.data is probably not the array you expect. The server may be returning an error or a successful response that isn't parseable as an array. To find out, print response.data to the console and confirm it's the array you expect.
Seems my API returned an object. I figured out the way around it by using Object.keys method and it worked. Here is the working code.
function getTime() {
var range = [53, 926, 8098];
var user = [];
for (var i = 0; i < range.length; i++) {
var auth = 'token';
var from = '2020-01-08'
var to = '2020-01-09'
var url = 'https://api.10000ft.com/api/v1/users/' + '449625' + '/time_entries?from=' + from + '&to=' + to + '&auth=' + auth;
var options = {
method: 'get',
headers: {
Authorization: 'Bearer ' + auth
}
};
var submitted_time_entries = {};
var response = UrlFetchApp.fetch(url, options);
var response = JSON.parse(response.getContentText());
var time_entries = response.data;
Object.keys(time_entries).forEach(function (time_entry) {
if (time_entry.user_id in submitted_time_entries) {
submitted_time_entries[time_entry.user_id] += time_entry.hours;
} else {
submitted_time_entries[time_entry.user_id] = time_entry.hours;
}
});
Object.keys(submitted_time_entries).forEach(function (user_id) {
if (submitted_time_entries[user_id] < 3) {
Logger.log(time_entry)
//send mail
}
});
}
}

How Do I add this javascript and HTML code into an angular project? and can i render html from javascript function in angular?

How Do I add this javascript and HTML code into an angular project ?
I have placed the func.js in a src folder in my angular project and in my app.component.ts file
where I tried to import and use ngAfterViewInit() to load and use the javascript functions
These are the javascript and html files I am trying to add to the angular web app:
funcs.js
const uName = 'admin';
const uPass = '12345';
const endpoint = 'http://11.11.111.241:8000';
const resource = {
questionnaire: 'Questionnaire',
valueset: 'ValueSet'
}
//get questionnaire
var url = 'http://cihi.ca/fhir/irrs/Questionnaire/abc-abc-community-on';
var quesJson = getData(resource.questionnaire, '?url=' + url);
quesJson = quesJson.entry[0].resource
// saveJsonToFile(quesJson, 'irrsQuesJson');
var copy = $.extend(true, {}, quesJson);
//convert to lhc form
var lformsQ = LForms.Util.convertFHIRQuestionnaireToLForms(quesJson, 'STU3')
// saveJsonToFile(lformsQ, 'lFormJson');
//prepare valuesets
const vsArray = createValueSetData();
//add value sets
injectValueSet(lformsQ);
// saveJsonToFile(lformsQ, 'lFormValueSetInjected');
// Add the form to the page
var options = { 'prepopulate': true };
LForms.Util.addFormToPage(lformsQ, 'formContainer', options);
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
function getData(res, param, log) {
var data = null;
var url = endpoint + '/' + res + param;
$.ajax({
accepts: {
json: 'application/fhir+json',
xml: 'application/fhir+xml'
},
dataType: 'json',
type: 'GET',
url: url,
async: false,
success: function (response) {
data = response;
if (log)
console.log('getData: SUCCESS - "' + url + '"');
},
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization", "Basic " + btoa(uName + ":" + uPass));
},
error: function (err) {
if (log)
console.error('getData: FAILED - "' + url + '"')
}
});
return data;
}
//recursively inject valueset into lhc json
function injectValueSet(lhcJson) {
if (lhcJson && 'items' in lhcJson) {
lhcJson.items.forEach(e => {
injectValueSet(e);
});
} else {
if ('answerValueSet' in lhcJson && 'reference' in lhcJson.answerValueSet) {
lhcJson['answers'] = vsArray[lhcJson.answerValueSet.reference];
}
}
}
//save form
function save() {
var quesResp = LForms.Util.getFormFHIRData('QuestionnaireResponse', 'STU3', '#formContainer');
saveJsonToFile(quesResp, 'questionnaireResponse' + '-' + new Date().getTime());
// var newLform = LForms.Util.mergeFHIRDataIntoLForms('QuestionnaireResponse', quesResp, lformsQ, 'STU3');
// LForms.Util.addFormToPage(newLform, 'formContainer2');
}
//open file
function openQues() {
var file = $('#file1')[0].files[0];
const fileReader = new FileReader();
fileReader.onload = event => {
var data = JSON.parse(event.target.result);
var lform = LForms.Util.mergeFHIRDataIntoLForms('QuestionnaireResponse', data, lformsQ, 'STU3');
injectValueSet(lformsQ);
LForms.Util.addFormToPage(lform, 'formContainer');
};
fileReader.onerror = error => console.error("Error loading file!");
fileReader.readAsText(file, "UTF-8");
}
// get valueSet count
function getValueSetCount() {
var count = 0;
var response = getData(resource.valueset, '?_summary=count');
if (response) {
count = response.total;
}
return count;
}
//get all valueSets id
function getValueSetIds() {
var ids = [];
var count = getValueSetCount();
var response = getData(resource.valueset, '?_count=' + count + '&_element=id');
if (response) {
if ('entry' in response && response.entry.length > 0) {
response.entry.forEach(e => {
if ('resource' in e && 'id' in e.resource && 'url' in e.resource) {
ids.push({
'id': e.resource.id,
'url': e.resource.url
});
}
});
}
}
return ids;
}
//create valueSet array for form fields
function createValueSetData() {
var data = {}, dataValueSet, failedIds;
var ids = getValueSetIds();
if (ids) {
failedIds = [];
ids.forEach(idSet => {
var response = getData(resource.valueset, '/' + idSet.id + '/$expand');
if (response && 'expansion' in response
&& 'contains' in response.expansion
&& response.expansion.contains.length > 0) {
dataValueSet = [];
response.expansion.contains.forEach(e => {
dataValueSet.push({
'text': e.code + ' - ' + e.display,
'code': e.code
});
});
data[idSet.url] = dataValueSet;
} else {
failedIds.push(idSet.id);
}
});
if (failedIds.length > 0) {
console.error("Failed fetching valueSets for the following IDs: \n Count: "
+ failedIds.length + "\n" + failedIds);
}
}
return data;
}
//save json to file
function saveJsonToFile(json, fileName) {
var textToSave = JSON.stringify(json);
var data = new Blob([textToSave], { type: 'text/plain' });
var textFileURL = window.URL.createObjectURL(data);
var hiddenElement = document.createElement('a');
hiddenElement.href = textFileURL;
hiddenElement.target = '_blank';
hiddenElement.download = fileName + '.txt';
hiddenElement.click();
}
**Html file :**
<!DOCTYPE html>
<html>
<head>
<link href="https://clinicaltables.nlm.nih.gov/lforms-versions/17.3.2/styles/lforms.min.css" media="screen"
rel="stylesheet" />
<link href="https://clinicaltables.nlm.nih.gov/autocomplete-lhc-versions/17.0.3/autocomplete-lhc.min.css"
rel="stylesheet" />
</head>
<body>
<button onclick="save()">
Save QuestionnaireResponse
</button>
<input type="file" id="file1">
<button onclick="openQues()">
Open QuestionnaireResponse
</button>
<div id="formContainer"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://clinicaltables.nlm.nih.gov/lforms-versions/17.3.2/lforms.min.js"></script>
<script src="https://clinicaltables.nlm.nih.gov/lforms-versions/17.3.2/fhir/STU3/lformsFHIR.min.js"></script>
<script src="https://clinicaltables.nlm.nih.gov/autocomplete-lhc-versions/17.0.3/autocomplete-lhc.min.js"></script>
<script src="./index.js"></script>
</body>
</html>
first create a new component through angular cli and add the variable declarations in .ts file i.e
const uName = 'admin';
const uPass = '12345';
const endpoint = 'http://11.11.111.241:8000';
const resource = {
questionnaire: 'Questionnaire',
valueset: 'ValueSet'
}
//get questionnaire
var url = 'http://cihi.ca/fhir/irrs/Questionnaire/abc-abc-community-on';
var quesJson = getData(resource.questionnaire, '?url=' + url);
quesJson = quesJson.entry[0].resource
// saveJsonToFile(quesJson, 'irrsQuesJson');
var copy = $.extend(true, {}, quesJson);
//convert to lhc form
var lformsQ = LForms.Util.convertFHIRQuestionnaireToLForms(quesJson, 'STU3')
// saveJsonToFile(lformsQ, 'lFormJson');
//prepare valuesets
const vsArray = createValueSetData();
//add value sets
injectValueSet(lformsQ);
// saveJsonToFile(lformsQ, 'lFormValueSetInjected');
// Add the form to the page
var options = { 'prepopulate': true };
LForms.Util.addFormToPage(lformsQ, 'formContainer', options);
then in .html page add the html code
<button onclick="save()">
Save QuestionnaireResponse
</button>
<input type="file" id="file1">
<button onclick="openQues()">
Open QuestionnaireResponse
</button>
<div id="formContainer"></div>
and then add the functions inside tag in the html file
function getData(res, param, log) {
var data = null;
var url = endpoint + '/' + res + param;
$.ajax({
accepts: {
json: 'application/fhir+json',
xml: 'application/fhir+xml'
},
dataType: 'json',
type: 'GET',
url: url,
async: false,
success: function (response) {
data = response;
if (log)
console.log('getData: SUCCESS - "' + url + '"');
},
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization", "Basic " + btoa(uName + ":" + uPass));
},
error: function (err) {
if (log)
console.error('getData: FAILED - "' + url + '"')
}
});
return data;
}
//recursively inject valueset into lhc json
function injectValueSet(lhcJson) {
if (lhcJson && 'items' in lhcJson) {
lhcJson.items.forEach(e => {
injectValueSet(e);
});
} else {
if ('answerValueSet' in lhcJson && 'reference' in lhcJson.answerValueSet) {
lhcJson['answers'] = vsArray[lhcJson.answerValueSet.reference];
}
}
}
//save form
function save() {
var quesResp = LForms.Util.getFormFHIRData('QuestionnaireResponse', 'STU3', '#formContainer');
saveJsonToFile(quesResp, 'questionnaireResponse' + '-' + new Date().getTime());
// var newLform = LForms.Util.mergeFHIRDataIntoLForms('QuestionnaireResponse', quesResp, lformsQ, 'STU3');
// LForms.Util.addFormToPage(newLform, 'formContainer2');
}
//open file
function openQues() {
var file = $('#file1')[0].files[0];
const fileReader = new FileReader();
fileReader.onload = event => {
var data = JSON.parse(event.target.result);
var lform = LForms.Util.mergeFHIRDataIntoLForms('QuestionnaireResponse', data, lformsQ, 'STU3');
injectValueSet(lformsQ);
LForms.Util.addFormToPage(lform, 'formContainer');
};
fileReader.onerror = error => console.error("Error loading file!");
fileReader.readAsText(file, "UTF-8");
}
// get valueSet count
function getValueSetCount() {
var count = 0;
var response = getData(resource.valueset, '?_summary=count');
if (response) {
count = response.total;
}
return count;
}
//get all valueSets id
function getValueSetIds() {
var ids = [];
var count = getValueSetCount();
var response = getData(resource.valueset, '?_count=' + count + '&_element=id');
if (response) {
if ('entry' in response && response.entry.length > 0) {
response.entry.forEach(e => {
if ('resource' in e && 'id' in e.resource && 'url' in e.resource) {
ids.push({
'id': e.resource.id,
'url': e.resource.url
});
}
});
}
}
return ids;
}
//create valueSet array for form fields
function createValueSetData() {
var data = {}, dataValueSet, failedIds;
var ids = getValueSetIds();
if (ids) {
failedIds = [];
ids.forEach(idSet => {
var response = getData(resource.valueset, '/' + idSet.id + '/$expand');
if (response && 'expansion' in response
&& 'contains' in response.expansion
&& response.expansion.contains.length > 0) {
dataValueSet = [];
response.expansion.contains.forEach(e => {
dataValueSet.push({
'text': e.code + ' - ' + e.display,
'code': e.code
});
});
data[idSet.url] = dataValueSet;
} else {
failedIds.push(idSet.id);
}
});
if (failedIds.length > 0) {
console.error("Failed fetching valueSets for the following IDs: \n Count: "
+ failedIds.length + "\n" + failedIds);
}
}
return data;
}
//save json to file
function saveJsonToFile(json, fileName) {
var textToSave = JSON.stringify(json);
var data = new Blob([textToSave], { type: 'text/plain' });
var textFileURL = window.URL.createObjectURL(data);
var hiddenElement = document.createElement('a');
hiddenElement.href = textFileURL;
hiddenElement.target = '_blank';
hiddenElement.download = fileName + '.txt';
hiddenElement.click();
}
and importantly add all the script imports to index.html the main index which is outside the app folder
add this in head section -
<link href="https://clinicaltables.nlm.nih.gov/lforms-versions/17.3.2/styles/lforms.min.css" media="screen"
rel="stylesheet" />
<link href="https://clinicaltables.nlm.nih.gov/autocomplete-lhc-versions/17.0.3/autocomplete-lhc.min.css"
rel="stylesheet" />
as well as this -
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://clinicaltables.nlm.nih.gov/lforms-versions/17.3.2/lforms.min.js"></script>
<script src="https://clinicaltables.nlm.nih.gov/lforms-versions/17.3.2/fhir/STU3/lformsFHIR.min.js"></script>
<script src="https://clinicaltables.nlm.nih.gov/autocomplete-lhc-versions/17.0.3/autocomplete-lhc.min.js"></script>
<script src="./index.js"></script>
last but not least add the selector of the created component in the app.component.html file
it should look something like this in created component of .html file add this to app.component.html
import { Component, OnInit } from '#angular/core';
import * as $ from 'jquery';
import {OpenQues,save} from '../assets/scripts.js'
declare var tesing: any;
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
title = 'Look jQuery Animation working in action!';
public ngOnInit()
{
$.getScript('./assets/scripts.js');
}
public open()
{
OpenQues();
}
public save()
{
save();
}
}
This worked for me

Creating an image file dynamically with Javascript

I'm trying to create an image file dynamically, based on the contents retrieved from S3 Bucket. Got CORS working fine, here's the code I've written:
/**
* #name fetchFile
* #desc Fetch the desired file, and add to our _filesPending array, and update dialog process
* #author cgervais
*/
var _filesPending = [];
var _fileMessageDialog = "Currently downloading {{numberOfFiles}} videos...";
var _filesDownloadedSoFar = 0;
var _filesDownloaded = [];
var downloading = false;
function OKDownload(response, fileName) {
var responsePerfect = {
link: function() {
var _tmpResponse = JSON.parse(response);
return _tmpResponse.location;
}
};
$.ajax({
type: "GET",
url: responsePerfect.link(),
data: {},
success: function(answer) {
var _tmpFileObject = {
fUrl: fileName,
fContent: btoa(unescape(encodeURIComponent(answer.trim())))
};
_filesDownloaded.push(_tmpFileObject);
_filesDownloadedSoFar = _filesDownloadedSoFar + 1;
console.log('Downloaded -- so far: ' + _filesDownloadedSoFar);
},
error: function(response, errorCode, errorMessage) {
console.log('[OKDownload] ' + response + ' - ' + errorCode + ' - ' + errorMessage + ' // ' + responsePerfect.link);
}
})
}
var _alreadyGeneratedRStrings = [];
function generateReasonableString(min, max, fnMax) {
var _genStringSeed = Date.now() + 10;
var _randomString = '';
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for( var i=min; i < max; i++ )
{
text += possible.charAt(Math.floor(Math.random() * possible.length));
}
_randomString = btoa(text + '::' + _genStringSeed);
if(_randomString.indexOf('==') > -1) {
_randomString = _randomString.replace('==','');
}
if(_randomString.length > fnMax) {
_randomString = _randomString.substring(0, fnMax);
}
if(_alreadyGeneratedRStrings.indexOf(_randomString) > -1) { _randomString = generateReasonableString(min, max, fnMax); }
_alreadyGeneratedRStrings.push(_randomString);
return _randomString;
}
function httpRawFetch(link) {
var matched = generateReasonableString(8, 26, 8) + ".jpg";
$.ajax({
type: "GET",
url: link.href + "&rawlink=yes",
data: {},
success: function(answer) {
if(answer === "") { console.log('[httpRawFetch] Failed fetching ' + link); return; }
OKDownload(answer, matched);
},
error: function(response, errorCode, errorMessage) {
console.log('[httpRawFetch] Error fetching JSON data from backend server.');
console.log('[DEBUG] ' + response + ' - ' + errorCode + ' - ' + errorMessage);
console.log('[DEBUG] Link: ' + link);
}
})
}
function generateDownloadModal() {
var _tmpHTML;
// #TODO: generate side modal with jQuery
}
function downloadFinished() {
var zip = new JSZip();
var _runningCountOfFiles = 0;
var _runningAddFiles = true;
for(var i = 0; i < _filesDownloaded.length; i++) {
_runningAddFiles = true;
// zip create file ( fileName, fileContent )
zip.file(_filesDownloaded[i].fUrl, decodeURIComponent(escape(atob(_filesDownloaded[i].fContent))));
_runningCountOfFiles++;
}
var recInterval = setInterval(function() {
if(_runningAddFiles && _runningCountOfFiles == _filesDownloaded.length || _runningCountOfFiles > _filesDownloaded.length) {
zip.generateAsync({type:"blob"})
.then(function(content) {
saveAs(content, "recordings.zip");
_runningAddFiles = false;
clearInterval(recInterval);
});
}
}, 1000);
}
setInterval(function() {
if(downloading) {
if(_filesDownloadedSoFar === _filesDownloaded.length) {
downloadFinished();
downloading = false;
}
}
}, 60000);
function fetchFile(link) {
if(link === "") {
alert('Cannot download this file.');
return;
}
_filesPending.push(link);
httpRawFetch(link);
downloading = true;
}
The issue:
It creates the zip with files, then it downloads to my machine. I open the image file, I get an error (all of them): "We can't open this file"
What am I doing wrong? They're JPG images.

Variable scope; var undefined or same var loop

Meteor.methods({
'list.messages' () {
getTwilioMessages(function(err, data) {
if (err) {
console.warn("There was an error getting data from twilio", err);
return
}
data.messages.forEach(function(message) {
if (SMS.find({
sid: message.sid
}).count() > 0) {
return;
}
var image;
if (message.numMedia > 0) {
var images = [];
Meteor.wrapAsync(client.messages(message.sid).media.list(function(err, data) {
console.log(data)
if (err) throw err;
Meteor.wrapAsync(data.media_list.forEach(function(media, index) {
mediaImage = (function() {
let mediaImg = 'http://api.twilio.com/2010-04-01/Accounts/' + media.account_sid + '/Messages/' + media.parent_sid + '/Media/' + media.sid;
return mediaImg
});
}));
images.push(mediaImage());
console.log("Just One:" + mediaImage())
console.log("IMAGESSSS " + mediaImage())
}));
message.image = mediaImage();
console.log("test" + image)
} else {
message.image = null
}
if (message.from === Meteor.settings.TWILIO.FROM) {
message.type = "outgoing";
} else {
message.type = "incoming";
}
SMS.insert(message)
});
});
getTwilioMessages();
Meteor.setInterval(getTwilioMessages, 60000);
// client.calls.get(function(err, response) {
// response.calls.forEach(function(call) {
// console.log('Received call from: ' + call.from);
// console.log('Call duration (in seconds): ' + call.duration);
// });
// });
},
I expect to see different image URL's in the data.media_list.forEach. But, it returns the same image. In the console I get the desired results.
I want these results:
message.image = 'http://api.twilio.com/2010-04-01/Accounts/3039030393/Messages/303030/media/3kddkdd'
message.image = 'http://api.twilio.com/2010-04-01/Accounts/3039sdfa393/Messages/303030/media/3asdfdfsa' inserted into the correct message.
instead I get the same URl over and over resulting in the same image
for all my messages. I guess my scope is incorrect, but I have
attempted to follow: 2ality guide on scoping and Explaining
JavaScript Scope And Closures with no luck.

Why Node.js script doesn't exit

I wrote code to get data from HTTP service and save it in MongoDB.
Now I test it directly from the console node script.js
The script does its job, but it doesn't exit. I have to do CTRL+C to stop it
Why does it not exit automatically? What place in the code is best for process.exit(0) (if it is needed)?
/*global Promise, getData, httpReq, searchData, getHotData, storeData*/
var http = require('http');
var CoubVideo = require('./models/coubdb.js');
function CoubApi (url, numPerPage, numOfPages) {
this.url = url;
this.numOfPages = numOfPages;
this.numPerPage = numPerPage;
this.getData = getData;
this.httpReq = httpReq;
this.searchData = searchData;
this.getHotData = getHotData;
this.storeData = storeData;
}
// Get data from server
function httpReq (url) {
var promise = new Promise (function (resolve, reject) {
http.get(url, function (res) {
var data = '';
res.on('data', function (chunk) {
data += chunk;
});
res.on('end', function () {
if(data.length > 0) {
resolve(JSON.parse(data));
} else {
reject("Error: HTTP request rejected!");
}
});
}).on('error', function (err) {
console.log(err);
});
});
return promise;
}
// Store data in MongoDB
function storeData (data, per_page) {
function insertVideoDoc (i) {
CoubVideo.count({id: data.coubs[i].id}, function (err, count) {
if (err) {
console.log(err);
}
if (count === 0 || count === null) {
var video = new CoubVideo(data.coubs[i]);
video.save(function (err) {
if (err) {
console.log(err);
}
console.log("Saved successfully!");
});
} else {
console.log("Duplicate");
}
});
}
var i;
for(i = 0; i < per_page; i++) {
insertVideoDoc(i);
}
}
// Search for coubs
function searchData (searchtext, order, page, per_page) {
var url = this.url +
"search?q=" + searchtext +
"&order_by=" + order +
"&per_page=" + per_page +
"&page=" + page;
this.httpReq(url).then(function (data) {
this.storeData(data, per_page);
}.bind(this));
}
// Get hot coubs
function getHotData (order, page, per_page) {
var url = this.url +
"timeline/hot?page=" + page +
"&per_page=" + per_page +
"&order_by=" + order;
this.httpReq(url).then(function (data) {
this.storeData(data, per_page);
}.bind(this));
}
// Get data
function getData () {
var i;
for(i = 0; i < this.numOfPages; i++) {
this.getHotData("newest_popular", i, this.numPerPage);
}
}
var coub = new CoubApi("http://coub.com/api/v2/", 2, 50);
coub.getData();

Categories

Resources