-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfilter-middleware.ts
More file actions
74 lines (63 loc) · 2.17 KB
/
Copy pathfilter-middleware.ts
File metadata and controls
74 lines (63 loc) · 2.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/**
* @typedef {import("../types.js").AttrValueFilter} AttrValueFilter
*/
import type {
AttrName,
AttrValue,
AttrValueFilter,
AttrValueFilterFallback,
} from '../types.js';
import {
filterFallback
} from './filter-fallback.js';
/**
* Creates a filter function from a collection of filters that returns
* the filtered value from the first filter that returns a value.
*
* @param {AttrValueFilter[]} filters - One or more attribute value
* middleware filter functions.
* @throws {TypeError} If the array of filters is too small.
* @throws {TypeError} If the filters are not functions.
* @returns {AttrValueFilter}
*/
export function createFilterMiddleware(
filters: AttrValueFilter[]
): AttrValueFilter {
if (!Array.isArray(filters) || filters.length < 1) {
throw new TypeError(
`createFilterMiddleware expected an array with at least 1 filter function`
);
}
// Define the tail variable to assign the fallback value or function
// from the constructed filter function.
let tailFallback: AttrValueFilterFallback;
const tailFilter = (value: unknown, name?: AttrName): AttrValue => filterFallback(value, name, tailFallback);
const stacker = (next: AttrValueFilter, filter: AttrValueFilter) => {
if (typeof filter !== 'function') {
throw new TypeError(
`createFilterMiddleware expected filter '${filter}' to be a function`
);
}
return (value: unknown, name?: AttrName): AttrValue => filter(value, name, next);
};
// Reverse the array to process middleware like a queue:
// first in, first out order (FIFO).
filters = Array.from(filters);
filters.reverse();
const middleware = filters.reduce(stacker, tailFilter);
/**
* Filters a value through the middleware stack,
* returning the first approved/filtered value.
*
* @type {AttrValueFilter}
*/
function filterMiddleware(
value: unknown,
name?: AttrName,
fallback: AttrValueFilterFallback = false
): AttrValue {
tailFallback = fallback;
return middleware(value, name);
}
return filterMiddleware;
}