From c4259dc3220c5df0108b1a5a17e046d93020bbba Mon Sep 17 00:00:00 2001 From: Leonardo Matos Date: Sat, 15 Feb 2020 02:10:42 -0300 Subject: [PATCH] fix(update-tokens): fix handling firestore query, env disable interval --- lib/services/update-tokens.js | 45 ++++++++++++++--------------------- 1 file changed, 18 insertions(+), 27 deletions(-) diff --git a/lib/services/update-tokens.js b/lib/services/update-tokens.js index 542c2a0..aa9edb1 100644 --- a/lib/services/update-tokens.js +++ b/lib/services/update-tokens.js @@ -1,59 +1,50 @@ 'use strict' -const admin = require('firebase-admin') -Date.prototype.addHours = function (value) { - this.setHours(this.getHours() + value); -} +const admin = require('firebase-admin') const updateTokens = (client) => { - const { dbFilename, db, table } = client + const { collRef, db, table } = client // handle access token refresh const refreshToken = require('./../methods/refresh-token')(client) - const handleRefreshToken = (row) => { + const handleRefreshToken = row => { + // start app authentication flux refreshToken(row.store_id, row.authentication_id).catch(err => { - // throw err console.error(err) }) } const task = () => { // refresh each access token every 8 hours - if (dbFilename) { + if (!collRef) { const query = 'SELECT authentication_id, store_id FROM ' + table + - ' WHERE updated_at < datetime("now", "-8 hours") OR updated_at IS NULL' + ' WHERE updated_at < datetime("now", "-8 hours") OR updated_at IS NULL' // run query and get each row object db.each(query, (err, row) => { if (!err) { - // start app authentication flux handleRefreshToken(row) } else { throw err } }) } else { - const ref = db.collection(table) - const queryDate = new Date() - queryDate.addHours(-8) - const queryFromDate = ref.where('updated_at', '<' , admin.firestore.Timestamp.fromDate(queryDate)).get() - const queryFromNull = ref.where('updated_at', '==', null).get() - let rows = [] - Promise.all([queryFromDate,queryFromNull]).then(values => { - values.map(item => { - rows = rows.concat(item.docs) - }) - if (rows && rows.length > 0) { - rows.map(row => { - handleRefreshToken(row.data()) + // working with Firestore collection + const date = new Date() + date.setHours(date.getHours() - 8) + + // run collection get query + collRef.where('updated_at', '<', admin.firestore.Timestamp.fromDate(date)) + .get().then(querySnapshot => { + querySnapshot.forEach(documentSnapshot => { + handleRefreshToken(documentSnapshot.data()) }) - } - }) + }) } } - // if database engine is sqlite, run task with 1 hour interval - if (dbFilename) { + if (process.env.ECOM_AUTH_UPDATE_INTERVAL !== 'disabled') { + // run task with 1 hour interval const hour = 60 * 60 * 1000 setInterval(task, hour) }