Skip to content

Commit

Permalink
fix(bling-client): update function get axios bling
Browse files Browse the repository at this point in the history
  • Loading branch information
wisley7l committed Oct 13, 2024
1 parent afdd171 commit 959c825
Show file tree
Hide file tree
Showing 3 changed files with 136 additions and 98 deletions.
57 changes: 39 additions & 18 deletions functions/lib/bling-auth/client.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,27 +14,28 @@ class Bling {
this.last_request = null
}

async checkTime (url) {
return new Promise(resolve => {
const now = new Date()
if (!this.last_request) {
this.last_request = now
resolve(true)
} else {
const timeout = now.getTime() - this.last_request.getTime()
if (timeout >= 1000) {
this.last_request = now
resolve(true)
} else {
setTimeout(() => {
this.last_request = new Date()
resolve(true)
}, 1000 - timeout)
}
}
async delay (timeout) {
return new Promise((resolve) => {
setTimeout(() => resolve(true), timeout)
})
}

async checkTime (url) {
const now = new Date()
if (!this.last_request) {
this.last_request = now
return true
}
const timeout = now.getTime() - this.last_request.getTime()
if (timeout >= 1000) {
this.last_request = new Date()
return true
}
await this.delay(1000 - timeout)
this.last_request = new Date()
return true
}

async get (url, opts) {
await this.checkTime(url)
if (!this._bling) {
Expand All @@ -47,6 +48,10 @@ class Bling {
const errorType = err.response.data.error?.type
if (errorType === 'TOO_MANY_REQUESTS') {
const isDailyRateLimitError = Boolean(err.response.data.error?.description?.includes('diário'))
if (!isDailyRateLimitError) {
await this.delay(1000)
return this._bling.get(url, opts)
}
this._bling = await blingAxios(this.clientId, this.clientSecret, this.storeId, timeForce, isDailyRateLimitError)
return this._bling.get(url, opts)
}
Expand All @@ -67,6 +72,10 @@ class Bling {
const errorType = err.response.data.error?.type
if (errorType === 'TOO_MANY_REQUESTS') {
const isDailyRateLimitError = Boolean(err.response.data.error?.description?.includes('diário'))
if (!isDailyRateLimitError) {
await this.delay(1000)
return this._bling.post(url, data, opts)
}
this._bling = await blingAxios(this.clientId, this.clientSecret, this.storeId, timeForce, isDailyRateLimitError)
return this._bling.post(url, data, opts)
}
Expand All @@ -87,6 +96,10 @@ class Bling {
const errorType = err.response.data.error?.type
if (errorType === 'TOO_MANY_REQUESTS') {
const isDailyRateLimitError = Boolean(err.response.data.error?.description?.includes('diário'))
if (!isDailyRateLimitError) {
await this.delay(1000)
return this._bling.patch(url, data, opts)
}
this._bling = await blingAxios(this.clientId, this.clientSecret, this.storeId, timeForce, isDailyRateLimitError)
return this._bling.patch(url, data, opts)
}
Expand All @@ -107,6 +120,10 @@ class Bling {
const errorType = err.response.data.error?.type
if (errorType === 'TOO_MANY_REQUESTS') {
const isDailyRateLimitError = Boolean(err.response.data.error?.description?.includes('diário'))
if (!isDailyRateLimitError) {
await this.delay(1000)
return this._bling.put(url, data, opts)
}
this._bling = await blingAxios(this.clientId, this.clientSecret, this.storeId, timeForce, isDailyRateLimitError)
return this._bling.put(url, data, opts)
}
Expand All @@ -127,6 +144,10 @@ class Bling {
const errorType = err.response.data.error?.type
if (errorType === 'TOO_MANY_REQUESTS') {
const isDailyRateLimitError = Boolean(err.response.data.error?.description?.includes('diário'))
if (!isDailyRateLimitError) {
await this.delay(1000)
return this._bling.delete(url)
}
this._bling = await blingAxios(this.clientId, this.clientSecret, this.storeId, timeForce, isDailyRateLimitError)
return this._bling.delete(url)
}
Expand Down
24 changes: 16 additions & 8 deletions functions/lib/bling-auth/create-access.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,8 @@ module.exports = async function (clientId, clientSecret, storeId, tokenExpiratio
// enable daily rate limit
await docRef.set({
isRateLimit: false,
updatedAt: now
updatedAt: now,
countErr: 0
}, { merge: true }).catch(logger.error)

throw new Error('Bling daily rate limit reached, please try again later')
Expand All @@ -45,7 +46,8 @@ module.exports = async function (clientId, clientSecret, storeId, tokenExpiratio
// disable daily rate limit
await docRef.set({
isRateLimit: false,
updatedAt: now
updatedAt: now,
countErr: 0
}, { merge: true }).catch(logger.error)
}

Expand All @@ -61,21 +63,27 @@ module.exports = async function (clientId, clientSecret, storeId, tokenExpiratio
await docRef.set({
...data,
updatedAt: now,
expiredAt: Timestamp.fromMillis(now.toMillis() + ((data.expires_in - 3600) * 1000))
expiredAt: Timestamp.fromMillis(now.toMillis() + ((data.expires_in - 3600) * 1000)),
countErr: 0
}, { merge: true })
accessToken = data.access_token
} catch (err) {
logger.warn(`Cant refresh Bling OAtuh token ${JSON.stringify({
logger.warn(`Cant refresh Bling OAuth token ${JSON.stringify({
url: err.config.url,
body: err.config.data,
response: err.response.data,
status: err.response.status
})}`)
const doc = await docRef.get()

await docRef.set({
isBloqued: true,
updatedAt: now
}, { merge: true }).catch(logger.error)
const countErr = doc.data().countErr || 0

if (countErr > 3) {
await docRef.set({
isBloqued: true,
updatedAt: now
}, { merge: true }).catch(logger.error)
}
throw err
}
}
Expand Down
153 changes: 81 additions & 72 deletions functions/routes/bling/callback.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,88 +2,97 @@ const { Timestamp, getFirestore } = require('firebase-admin/firestore')
const { logger } = require('../../context')
const { nameCollectionEvents } = require('../../__env')
const checkApiBling = require('../../lib/bling-auth/check-enable-api')
// const getAppData = require('./../../lib/store-api/get-app-data')

exports.post = async ({ appSdk, admin }, req, res) => {
// const blingToken = req.query.token
const storeId = parseInt(req.query.store_id, 10)
if (storeId > 100 && req.body) {
const isApiBlingOk = await checkApiBling(storeId)
try {
// const blingToken = req.query.token
const storeId = parseInt(req.query.store_id, 10)
if (storeId > 100 && req.body) {
await appSdk.getAuth(storeId)
// const appData = await getAppData({ appSdk, storeId, auth })

if (!isApiBlingOk) {
logger.warn('> Error in request to api Bling')
return res.sendStatus(403)
}

logger.info(`storeId: ${storeId} ${JSON.stringify(req.body)}`)
const isApiBlingOk = await checkApiBling(storeId)

let { retorno } = req.body
if (!retorno && typeof req.body.data === 'string') {
try {
const data = JSON.parse(req.body.data)
retorno = data.retorno
} catch (e) {
if (!isApiBlingOk) {
logger.warn('> Error in request to api Bling')
return res.sendStatus(403)
}
}
const now = Timestamp.now()
const body = {
eventBy: 'bling',
storeId,
action: 'importation',
createdAt: now,
mustUpdateAppQueue: false,
canCreateNew: false,
isHiddenQueue: true
}

const promises = []
logger.info(`storeId: ${storeId} ${JSON.stringify(req.body)}`)

if (retorno) {
if (retorno.pedidos && retorno.pedidos.length) {
retorno.pedidos.forEach(({ pedido }) => {
console.log(`${JSON.stringify(pedido)}`)
const { numero } = pedido
const resourceId = `${numero}`
const docRef = getFirestore()
.doc(`queue/${storeId}/${nameCollectionEvents}/order_${numero}`)
promises.push(docRef.set({
...body,
resourceId,
queue: 'order_numbers',
_blingId: numero
}, { merge: true })
.catch(logger.error)
)
})
let { retorno } = req.body
if (!retorno && typeof req.body.data === 'string') {
try {
const data = JSON.parse(req.body.data)
retorno = data.retorno
} catch (e) {
}
}
const now = Timestamp.now()
const body = {
eventBy: 'bling',
storeId,
action: 'importation',
createdAt: now,
mustUpdateAppQueue: false,
canCreateNew: false,
isHiddenQueue: true
}

if (retorno.estoques && retorno.estoques.length) {
retorno.estoques.forEach(({ estoque }) => {
const { id, codigo } = estoque
const resourceId = `${codigo};:`
const docRef = getFirestore()
.doc(`queue/${storeId}/${nameCollectionEvents}/product_${id}`)
promises.push(docRef.set({
...body,
resourceId,
queue: 'skus',
_blingId: id
}, { merge: true })
.catch(logger.error)
)
})
const promises = []

if (retorno) {
if (retorno.pedidos && retorno.pedidos.length) {
retorno.pedidos.forEach(({ pedido }) => {
console.log(`${JSON.stringify(pedido)}`)
const { numero } = pedido
const resourceId = `${numero}`
const docRef = getFirestore()
.doc(`queue/${storeId}/${nameCollectionEvents}/order_${numero}`)
promises.push(docRef.set({
...body,
resourceId,
queue: 'order_numbers',
_blingId: numero
}, { merge: true })
.catch(logger.error)
)
})
}

if (retorno.estoques && retorno.estoques.length) {
retorno.estoques.forEach(({ estoque }) => {
const { id, codigo } = estoque
const resourceId = `${codigo};:`
const docRef = getFirestore()
.doc(`queue/${storeId}/${nameCollectionEvents}/product_${id}`)
promises.push(docRef.set({
...body,
resourceId,
queue: 'skus',
_blingId: id
}, { merge: true })
.catch(logger.error)
)
})
}
await Promise.all(promises)
return res.sendStatus(200)
/*
TODO: check Bling server IPs
const clientIp = req.get('x-forwarded-for') || req.connection.remoteAddress
*/
} else {
logger.log(`#${storeId} unexpected Bling callback: ${JSON.stringify(req.body)}`)
return res.status(200)
.send('Ignoring invalid request body')
}
await Promise.all(promises)
return res.sendStatus(200)
/*
TODO: check Bling server IPs
const clientIp = req.get('x-forwarded-for') || req.connection.remoteAddress
*/
} else {
logger.log(`#${storeId} unexpected Bling callback: ${JSON.stringify(req.body)}`)
return res.status(200)
.send('Ignoring invalid request body')
}
}

return res.sendStatus(403)
return res.sendStatus(403)
} catch (err) {
logger.error(err)
return res.sendStatus(500)
}
}

0 comments on commit 959c825

Please sign in to comment.