Skip to content

Commit

Permalink
fix(update-tokens): fix handling firestore query, env disable interval
Browse files Browse the repository at this point in the history
  • Loading branch information
leomp12 committed Feb 15, 2020
1 parent 9579f7e commit c4259dc
Showing 1 changed file with 18 additions and 27 deletions.
45 changes: 18 additions & 27 deletions lib/services/update-tokens.js
Original file line number Diff line number Diff line change
@@ -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)
}
Expand Down

0 comments on commit c4259dc

Please sign in to comment.