diff --git a/src/addons.js b/src/addons.js new file mode 100644 index 0000000..0a29691 --- /dev/null +++ b/src/addons.js @@ -0,0 +1,23 @@ +export default class AddonsManager { + addons = new Map() + + register(name, addon) { + this.addons.set(name, addon) + } + + get(name) { + return this.addons.get(name) + } + + // search all addons registered, and find all addons that has a addon[operation] function + getByOperation(operation) { + return Array.from(this.addons.values()) + .filter((addon) => addon[operation]) + .map((addon) => { + return { + id: addon.constructor.id, + fn: addon[operation], + } + }) + } +} diff --git a/src/helpers/processWithAddons.js b/src/helpers/processWithAddons.js new file mode 100644 index 0000000..5f2c5c9 --- /dev/null +++ b/src/helpers/processWithAddons.js @@ -0,0 +1,30 @@ +export default async function processAddons({ + operation, + initialData, + fnArguments, + normalizeAddonResult, +}) { + const addons = __comty_shared_state.addons.getByOperation(operation) + + let processedData = initialData + + if (typeof fnArguments === "undefined") { + fnArguments = [] + } + + for (const addon of addons) { + try { + const addonResult = await addon.fn(...fnArguments) + + processedData = normalizeAddonResult({ + operation, + currentData: processedData, + addonResult, + }) + } catch (error) { + console.error(`Error in [${operation}] addon:`, error) + } + } + + return processedData +}