#Whats the correct hook to update localizations?

6 messages · Page 1 of 1 (latest)

willow meadow
#

I try to auto-translate and modify different locales on collection save (afterChange hook).

I tried the following pattern to avoid infinte loops, however the payload.update({options}) call seems to block indefinitly.
I use the Postgres DB adapter and the 3.0.0.-beta.59 build.

Here`s my snippet:

const translateLocalesAfterChange: CollectionAfterChangeHook = async ({
  collection, // collection name
  context, // context object
  doc, // full document data
  req, // full express request
  previousDoc, // document data before updating the collection
  operation, // name of the operation ie. 'create', 'update'
}) => {

  if (context.autoTranslateRunning) {
    console.log("AutoTranslate is already running, skipping")
    return doc
  }

 
  for (let localeCode of ['de','pt','fr']) {

    /// [...] DO some stuff, like translating from the source language
    let translated_localized = { "title": "translated title"}
    
    let options = {
      id: doc.id,      // this is always the same doc id
      collection: 'documents',
      data: translated_localized as Partial<Document>,
      locale: localeCode ,
      context: {
        autoTranslateRunning: true // set the context flag
      }
    }
  
    // THE NEXT LINE SEEMS TO BLOCK FOREVER
    await req.payload.update(options);
  }
}

... any ideas / hints what could be wrong?

river ospreyBOT
willow meadow
#

Something is not right... if I wrap req.payload.update(...) in a setTimeout, it seems to work, but seems like some race condition, e.g. sometimes locales get updated, sometimes not..

nova plank
jovial mica
#

Woaw, thank you so much @nova plank, don't know how you found that but I'm so glad I saw your answer after this day of tries and fails 🙏

nova plank
#

You're welcome @jovial mica. I found it by pure luck. I think it's something that should be included on the docs (I'd do it myself if I knew exactly why it worked...)