javascript / expert
Snippet
Composable Factory Pattern with Functional Middleware Pipeline
By applying the functional compose/reduceRight pattern to Vue state management, higher-order composables can intercept, modify, or halt reactive updates through an extensible middleware chain.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import { ref } from 'vue';export function createMiddlewareComposable(...middlewares) {return function usePipelineInitialiser(initialValue) {const state = ref(initialValue);const dispatch = async (action) => {const runner = middlewares.reduceRight((next, middleware) => (ctx) => middleware(ctx, next),async (ctx) => { ctx.state.value = ctx.action.payload; });await runner({ state, action });};return { state, dispatch };};}
vue
Breakdown
1
(next, middleware) => (ctx) => middleware(ctx, next)
Chains functions dynamically in reverse order to form a nested execution stack.
2
async (ctx) => { ctx.state.value = ctx.action.payload; }
Acts as the terminal reducer updating the root reactive ref value.
3
await runner({ state, action });
Triggers execution through the entire asynchronous middleware pipeline.