Continue failed batchPlay chain

I went with idea of manually continuing descriptors after failure. Luckily, result contains both successes and failures so it’s easy to find an index where to slice.

const ps = require("photoshop")
import { Logger } from "../../common/logger"
import { removeEmpty } from "../../utils"

export const batchPlay = async (
  descriptors,
  options = { debug: false, continue: false, history: undefined }
) => {
  const prefix = "[batchPlay debug]"
  const { debug, history } = options
  const l = Logger(debug, prefix)
  var historyState = undefined
  if (history) {
    historyState = {
      name: history,
      target: {
        _ref: "document",
        _enum: "ordinal",
        _value: "targetEnum",
      },
    }
  }
  l.log("batchPlay", JSON.stringify(descriptors, " ", 2))
  try {
    const result = await ps.action.batchPlay(
      descriptors,
      removeEmpty({
        synchronousExecution: false,
        modalBehavior: "fail",
        historyStateInfo: historyState,
        ...options,
      })
    )
    result.forEach((item, index) => {
      if (item.message) {
        Logger(true, prefix).error(
          ">>> Descriptor failed",
          descriptors[index],
          item.message
        )
        throw {
          message: item.message,
          continuation: descriptors.slice(index + 1),
        }
      }
    })
    return result
  } catch (payload) {
    if (!options.continue) {
      throw payload.message
    }

    const { continuation } = payload
    l.log("continue with", descriptors)

    return await batchPlay(continuation, options)
  }
}
2 Likes