Skip to content

Commit

Permalink
chore(import-images): update handle import images
Browse files Browse the repository at this point in the history
  • Loading branch information
wisley7l committed Sep 11, 2024
1 parent 6a9f249 commit 80cdd76
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 47 deletions.
17 changes: 6 additions & 11 deletions functions/lib/integration/handle-images/import-images.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,8 @@
// const getAppData = require('../store-api/get-app-data')
const { logger } = require('../../../context')
const { Timestamp } = require('firebase-admin/firestore')
const { getAppSdk, saveImagesProduct } = require('./utils')
const { getAppSdk, saveImagesProduct, getProductById } = require('./utils')

const getProductById = (appSdk, storeId, auth, productId) => appSdk
.apiRequest(storeId, `/products/${productId}.json`, 'GET', null, auth)
.then(({ response }) => response.data)
.catch(logger.error)
module.exports = async (change, context) => {
const { docId } = context.params
if (!change.after.exists) {
Expand Down Expand Up @@ -37,17 +33,16 @@ module.exports = async (change, context) => {
const appSdk = await getAppSdk()
const auth = await appSdk.getAuth(storeId)
const promises = await Promise.all([
// getAppData({ appSdk, storeId, auth }, true),
getProductById(appSdk, storeId, auth, productId),
doc.ref.set({ processingAt: now }, { merge: true })
])
// const appData = promises[0]
const product = promises[0]
// logger.info(`${JSON.stringify(product)} anexos: ${JSON.stringify(anexos)}`)
saveImagesProduct({ appSdk, storeId, auth }, product, anexos)
}

// logger.info(`${storeId} ${productId} ${JSON.stringify(anexos)}`)
return saveImagesProduct({ appSdk, storeId, auth }, product, anexos)
.then(async () => doc.ref.delete())
.then(() => logger.info(`>Finish[${docId}]`))
.catch(logger.error)
}
}
return null
}
88 changes: 52 additions & 36 deletions functions/lib/integration/handle-images/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,15 @@ const getAppSdk = () => {
})
}

const tryImageUpload = (storeId, auth, originImgUrl, product, isRetry) => new Promise(resolve => {
const getProductById = (appSdk, storeId, auth, productId) => appSdk
.apiRequest(storeId, `/products/${productId}.json`, 'GET', null, auth)
.then(({ response }) => response.data)
.catch(logger.error)

const updateProductById = (appSdk, storeId, auth, productId, body) => appSdk
.apiRequest(storeId, `/products/${productId}.json`, 'PATCH', body, auth)

const tryImageUpload = (storeId, auth, originImgUrl, product, index, isRetry) => new Promise(resolve => {
axios.get(originImgUrl, {
responseType: 'arraybuffer'
})
Expand Down Expand Up @@ -57,9 +65,9 @@ const tryImageUpload = (storeId, auth, originImgUrl, product, isRetry) => new Pr

.catch(err => {
if (err.name !== 'Unexpected Storage API response' && !isRetry) {
setTimeout(tryImageUpload(storeId, auth, originImgUrl, product, true), 700)
setTimeout(tryImageUpload(storeId, auth, originImgUrl, product, index, true), 700)
} else {
console.error(err)
logger.error(err)
resolve({
_id: ecomUtils.randomObjectId(),
normal: {
Expand All @@ -71,22 +79,22 @@ const tryImageUpload = (storeId, auth, originImgUrl, product, isRetry) => new Pr
})
})

// .then(picture => {
// if (product && product.pictures) {
// if (index === 0 || index) {
// product.pictures[index] = picture
// } else {
// product.pictures.push(picture)
// }
// }
// return picture
// })
.then(picture => {
if (product && product.pictures) {
if (index === 0 || index) {
product.pictures[index] = picture
} else {
product.pictures.push(picture)
}
}
return picture
})

const saveImagesProduct = async ({ appSdk, storeId, auth }, product, anexos) => {
if (!product.pictures) {
product.pictures = []
}
// const promises = []
const promisesImgs = []
anexos.forEach((anexo, i) => {
let url
if (anexo && anexo.anexo) {
Expand All @@ -101,39 +109,47 @@ const saveImagesProduct = async ({ appSdk, storeId, auth }, product, anexos) =>
if (product.pictures.length) {
const pathImg = url.split('/')
const nameImg = pathImg[pathImg.length - 1]
const oldPictureIndex = product.pictures.findIndex(({ normal }) => normal.url.includes(nameImg))
const oldPictureIndex = product.pictures.length
? product.pictures.findIndex(({ normal }) => normal.url.includes(nameImg))
: -1

if (oldPictureIndex > -1) {
index = oldPictureIndex
const oldPicture = product.pictures[oldPictureIndex]
isImgExists = oldPicture.normal.url !== url
}
}

logger.info(`${product._id} ${JSON.stringify(product.picture)} exists: ${isImgExists} index: ${index} (${i}) ${url}`)
// const pictureExis
// if (!isImgExists) {
// }
// promises.push(tryImageUpload(storeId, auth, url, product, i))
logger.info(`${product._id} ${JSON.stringify(product.pictures)} exists: ${isImgExists} index: ${index} (${i}) ${url}`)
if (!isImgExists) {
promisesImgs.push(tryImageUpload(storeId, auth, url, product, i))
}
}
})
return Promise.all(promisesImgs).then((images) => {
const body = {
pictures: product.pictures
}
if (Array.isArray(product.variations) && product.variations.length) {
product.variations.forEach(variation => {
if (variation.picture_id || variation.picture_id === 0) {
const variationImage = images[variation.picture_id]
if (variationImage._id) {
variation.picture_id = variationImage._id
} else {
delete variation.picture_id
}
}
})
body.variations = product.variations
}
logger.info(`Update product ${product._id} => ${JSON.stringify(body)}`)
return updateProductById(appSdk, storeId, auth, product._id, body)
})
// return Promise.all(promises).then((images) => {
// if (Array.isArray(product.variations) && product.variations.length) {
// product.variations.forEach(variation => {
// if (variation.picture_id || variation.picture_id === 0) {
// const variationImage = images[variation.picture_id]
// if (variationImage._id) {
// variation.picture_id = variationImage._id
// } else {
// delete variation.picture_id
// }
// }
// })
// }
// return resolve(product)
// })
}

module.exports = {
saveImagesProduct,
getAppSdk
getAppSdk,
getProductById
}

0 comments on commit 80cdd76

Please sign in to comment.