Я настроил API gmail, чтобы каждые 10 секунд я мог получать последние 5 сообщений из своего почтового ящика. Вот мой код:
gmail.users.messages.list(
{ auth: auth, userId: 'me', maxResults: 5 },
function(err, response) {
if (err) {
console.log('The API returned an error: ' + err)
return
}
console.log('+ 5, Listing Messages')
response.data.messages.forEach(message => {
console.log('Got message id: ' + message['id'])
const id = message['id']
gmail.users.messages.get({ auth: auth, userId: 'me', id: id }, function(
err,
response
) {
if (err) {
console.log('The API returned an error: ' + err)
return
}
console.log('+ 5 Getting message')
const fromHeader = response['data'].payload.headers.filter(
header => header.name === 'From'
)[0]
if (fromHeader.value.includes('amarciniak@bcit.ca')) {
response.data.payload.parts.forEach(part => {
if (
part.filename !== '' &&
part.mimeType ===
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
) {
console.log('For Each Part')
gmail.users.messages.attachments.get(
{
userId: 'me',
messageId: id,
id: part.body.attachmentId,
},
(err, { data }) => {
if (err) {
return console.log('Error getting attachment: ' + err)
}
console.log('+ 5 Getting attachment')
const hash = crypto
.createHash('md5')
.update(data['data'])
.digest('hex')
const newFileName = `${fileFolderPath}/${hash}_${part.filename}`
const filesInFolder = fs.readdirSync(fileFolderPath)
if (!filesInFolder.includes(`${hash}_${part.filename}`)) {
fs.writeFile(
newFileName,
data['data'],
{ encoding: 'base64' },
err => {
if (err) {
console.log(err)
} else {
console.log(`Wrote File: ${newFileName}`)
}
}
)
} else {
console.log(
`No changes detected. File: ${newFileName} is already present in folder. `
)
}
}
)
}
})
}
})
})
}
)
}
Я получаю список сообщений из gmail, затем для всех 5 сообщений я получаю отдельные сообщения, затем для каждого сообщения я получаю части полезной нагрузки, которые для каждой части я получаю вложение и что-то с ним делать. Каждый из моих запросов get использует 5 баллов «квоты». Из gmail api docs ограничение составляет 250 в секунду. В этом фрагменте кода я не вижу, как я могу использовать более 250 квот в секунду. Самое большее, я использую 5 * 5 * 5 или около того. так нравится 125 баллов. Ограничивает ли это скорость, потому что эти запросы происходят так быстро один за другим, как 125 баллов за 100 мс, что на самом деле равно 1250 баллам в секунду? Это так работает? Или мой код работает намного чаще, чем я думаю?