Skip to content

Commit de44910

Browse files
committed
Fixed rate limiting for gsheets
1 parent 43718ce commit de44910

File tree

1 file changed

+27
-3
lines changed

1 file changed

+27
-3
lines changed

src/server/services/gSheet.js

Lines changed: 27 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,12 @@ const getCircularReplacer = () => {
2525
* APIs in the same uniform manner.
2626
*/
2727
export default class GSheetService {
28+
constructor() {
29+
this.getSheetAPI = this.getSheetAPI.bind(this);
30+
this.addToSheetAPI = this.getSheetAPI.bind(this);
31+
this.addToSheet = this.getSheetAPI.bind(this);
32+
}
33+
2834
/**
2935
* getSheet
3036
* @param {Object} req the request
@@ -45,7 +51,13 @@ export default class GSheetService {
4551
rows: JSON.parse(rowsJson),
4652
});
4753
} catch (e) {
48-
res.status((e.response && e.response.status) || 500);
54+
const status = (e.response && e.response.status) || 500;
55+
if (status === 429) {
56+
// rate limit issue - wait 15sec and retry
57+
await new Promise(resolve => setTimeout(resolve, 15000));
58+
return this.getSheetAPI(req, res);
59+
}
60+
res.status(status);
4961
return res.send((e.response && e.response.data) || { ...e, message: e.message });
5062
}
5163
}
@@ -65,7 +77,7 @@ export default class GSheetService {
6577
// set credentials for working
6678
await doc.useServiceAccountAuth({
6779
client_email: config.GOOGLE_SERVICE_ACCOUNT_EMAIL,
68-
private_key: config.GOOGLE_SERVICE_ACCOUNT_PRIVATE_KEY.replace(new RegExp('\\\\n', 'g'), '\n'),
80+
private_key: config.GOOGLE_SERVICE_ACCOUNT_PRIVATE_KEY.replace(/\\m/g, '\n'),
6981
});
7082
// load doc infos
7183
await doc.loadInfo();
@@ -77,7 +89,13 @@ export default class GSheetService {
7789
rows: JSON.parse(rowsJson),
7890
});
7991
} catch (e) {
80-
res.status((e.response && e.response.status) || 500);
92+
const status = (e.response && e.response.status) || 500;
93+
if (status === 429) {
94+
// rate limit issue - wait 15sec and retry
95+
await new Promise(resolve => setTimeout(resolve, 15000));
96+
return this.addToSheetAPI(req, res);
97+
}
98+
res.status(status);
8199
return res.send((e.response && e.response.data) || { ...e, message: e.message });
82100
}
83101
}
@@ -105,6 +123,12 @@ export default class GSheetService {
105123
const rowsJson = JSON.stringify(moreRows, getCircularReplacer());
106124
return rowsJson;
107125
} catch (e) {
126+
const status = (e.response && e.response.status) || 500;
127+
if (status === 429) {
128+
// rate limit issue - wait 15sec and retry
129+
await new Promise(resolve => setTimeout(resolve, 15000));
130+
return this.addToSheet(id, payload, index);
131+
}
108132
return e;
109133
}
110134
}

0 commit comments

Comments
 (0)