-
-
Notifications
You must be signed in to change notification settings - Fork 375
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: add in example of multi-plugin extensions
- Loading branch information
1 parent
5aeb2ef
commit c6cb209
Showing
1 changed file
with
57 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,57 @@ | ||
const defaults = { | ||
plugins: [], | ||
enabled: true | ||
} | ||
|
||
const multiPlugin = (opts = {}) => { | ||
const { plugins, enabled } = { ...defaults, ...opts } | ||
if (!enabled) { | ||
return {} | ||
} | ||
|
||
const flows = { | ||
beforePrefetch: [], | ||
requestStart: [], | ||
beforeMiddleware: [], | ||
afterMiddleware: [], // reveresed | ||
beforeHandler: [], | ||
afterHandler: [], // reveresed | ||
requestEnd: [] // reveresed | ||
} | ||
|
||
const push = (id, plugin) => { | ||
if (plugin[id]) { | ||
flows[id].push(plugin[id]) | ||
} | ||
} | ||
for (let i = 0, l = plugins.length; i < l; i++) { | ||
const plugin = plugins[i] | ||
push('beforePrefetch', plugin) | ||
push('requestStart', plugin) | ||
push('beforeMiddleware', plugin) | ||
push('afterMiddleware', plugin) | ||
push('beforeHandler', plugin) | ||
push('afterHandler', plugin) | ||
push('requestEnd', plugin) | ||
} | ||
|
||
flows.afterMiddleware.reverse() | ||
flows.afterHandler.reverse() | ||
flows.requestEnd.reverse() | ||
|
||
const run = (id) => { | ||
for (let i = 0, l = flows[id].length; i < l; i++) { | ||
flows[id]() | ||
} | ||
} | ||
return { | ||
beforePrefetch: () => run('beforePrefetch'), | ||
requestStart: () => run('requestStart'), | ||
beforeMiddleware: () => run('beforeMiddleware'), | ||
afterMiddleware: () => run('afterMiddleware'), | ||
beforeHandler: () => run('beforeHandler'), | ||
afterHandler: () => run('afterHandler'), | ||
requestEnd: () => run('requestEnd') | ||
} | ||
} | ||
export default multiPlugin |