|
| 1 | +// Adapted from @wq/app |
| 2 | + |
| 3 | +let pcount = 0; |
| 4 | + |
| 5 | +export function registerPlugin(store, plugin) { |
| 6 | + if (store._store) { |
| 7 | + throw new Error("Store already initialized!"); |
| 8 | + } |
| 9 | + if (Array.isArray(plugin)) { |
| 10 | + plugin.forEach((p) => registerPlugin(store, p)); |
| 11 | + return; |
| 12 | + } |
| 13 | + if (plugin.dependencies) { |
| 14 | + registerPlugin(store, plugin.dependencies); |
| 15 | + } |
| 16 | + if (store.plugins[plugin.name]) { |
| 17 | + if (store.plugins[plugin.name] === plugin) { |
| 18 | + return; |
| 19 | + } else { |
| 20 | + throw new Error( |
| 21 | + `${store.name} store already has a plugin named ${plugin.name}!` |
| 22 | + ); |
| 23 | + } |
| 24 | + } |
| 25 | + pcount++; |
| 26 | + if (!plugin.name) { |
| 27 | + plugin.name = "plugin" + pcount; |
| 28 | + } |
| 29 | + store.plugins[plugin.name] = plugin; |
| 30 | + plugin.store = store; |
| 31 | +} |
| 32 | + |
| 33 | +export function applyPlugins(store, config) { |
| 34 | + for (const [name, plugin] of Object.entries(store.plugins)) { |
| 35 | + if (plugin.ajax) { |
| 36 | + config.ajax = plugin.ajax.bind(plugin); |
| 37 | + } |
| 38 | + if (plugin.reducer) { |
| 39 | + let persist = false, |
| 40 | + restore = null; |
| 41 | + if (typeof plugin.persist === "function") { |
| 42 | + persist = plugin.persist.bind(plugin); |
| 43 | + restore = plugin.restore |
| 44 | + ? plugin.restore.bind(plugin) |
| 45 | + : (state) => state; |
| 46 | + } else if (plugin.persist) { |
| 47 | + persist = true; |
| 48 | + } |
| 49 | + store.addReducer( |
| 50 | + name, |
| 51 | + (state, action) => plugin.reducer(state, action), |
| 52 | + persist, |
| 53 | + restore |
| 54 | + ); |
| 55 | + } |
| 56 | + if (plugin.actions) { |
| 57 | + Object.assign(plugin, store.bindActionCreators(plugin.actions)); |
| 58 | + } |
| 59 | + if (plugin.subscriber) { |
| 60 | + store.subscribe(() => plugin.subscriber(store.getState())); |
| 61 | + } |
| 62 | + } |
| 63 | +} |
| 64 | + |
| 65 | +export async function initPlugins(store, config) { |
| 66 | + for (const plugin of Object.values(store.plugins)) { |
| 67 | + if (plugin.init) { |
| 68 | + await plugin.init(config && config[plugin.name]); |
| 69 | + } |
| 70 | + } |
| 71 | +} |
0 commit comments