I’m calling an API and getting data going through its pagination. When I get to the last page, though, the obejct giving me the last page is empty and it’s throwing the following error: TypeError: Cannot convert undefined or null to object
Besides, I don’t any data from that last page.
Here’s the pagination information I get:
JavaScript
x
13
13
1
{"count":100,"total":545,"_links":
2
{
3
"self":{
4
"href":"/candidates?page=0&per_page=100"
5
},
6
"next":{
7
"href":"/candidates?per_page=100"
8
},
9
"last":{
10
"href":"/candidates?page=6&per_page=100"
11
}
12
},
13
Here’s the code I’m using to get the data:
JavaScript
1
49
49
1
function allcandidates() {
2
const url = "https://api.catsone.com/v3/candidates";
3
const params = {
4
'muteHttpExceptions': true,
5
'method': 'GET',
6
'redirect': 'follow',
7
'headers': {
8
'Content-Type': 'application/json',
9
'Authorization': 'Token ' + API_KEY
10
}
11
};
12
13
let pageNum = 1;
14
let lastPgNo;
15
16
let data = {}, output = [];
17
18
do {
19
let currentUrl = url + '?' + 'per_page=100' + '&' + 'page=' + pageNum;
20
//One of their URL parameter is "per_page", which is 25 result/page and it go up to 100. I'm not sure if the fact that the last page doesn't have all 100 results may result in an error, too.
21
22
const response = UrlFetchApp.fetch(currentUrl, params);
23
const respCode = response.getResponseCode();
24
if (respCode != 200) {
25
Browser.msgBox('The server seems to be temporarily down. Please try again later.');
26
return;
27
}
28
//Gets the last page number
29
const getText = response.getContentText();
30
const lastPageObj = JSON.parse(getText)['_links']['last'];
31
const lastPgVal = Object.values(lastPageObj); //This is where the error occurs
32
const lastPgText = lastPgVal.toString();
33
lastPgNo = Number(lastPgText.split('?page=').pop().split('&')[0])
34
35
//Gets current page
36
const currentPageObj = JSON.parse(getText)['_links']['self'];
37
const currentPgVal = Object.values(currentPageObj);
38
const nextPgText = currentPgVal.toString();
39
var currentPgNo = Number(nextPgText.split('?page=').pop().split('&')[0])
40
41
const dataSet = JSON.parse(getText)['_embedded']['candidates'];
42
for (let i = 0; i < dataSet.length; i++) {
43
data = dataSet[i];
44
output.push([data.id]);
45
}
46
pageNum = pageNum + 1;
47
} while (pageNum <= lastPgNo);
48
}
49
Advertisement
Answer
You might use an if
statement and continue
. I.E. replace
JavaScript
1
2
1
const lastPgVal = Object.values(lastPageObj);
2
by
JavaScript
1
6
1
if(lastPageObj){
2
const lastPgVal = Object.values(lastPageObj);
3
} else {
4
continue;
5
}
6
Another option is to use try...catch
Resources