Allow non-tuple values
This commit is contained in:
parent
2d7d2da964
commit
f2f4dd7b8e
@ -13,10 +13,10 @@ import {
|
|||||||
const msg = await readStdin();
|
const msg = await readStdin();
|
||||||
|
|
||||||
const result = await pipeline(msg, [
|
const result = await pipeline(msg, [
|
||||||
[noopPolicy],
|
noopPolicy,
|
||||||
[hellthreadPolicy, { limit: 100 }],
|
[hellthreadPolicy, { limit: 100 }],
|
||||||
[antiDuplicationPolicy],
|
antiDuplicationPolicy,
|
||||||
[rateLimitPolicy],
|
rateLimitPolicy,
|
||||||
]);
|
]);
|
||||||
|
|
||||||
writeStdout(result);
|
writeStdout(result);
|
||||||
|
@ -1,15 +1,17 @@
|
|||||||
import { InputMessage, OutputMessage, Policy } from './types.ts';
|
import { InputMessage, OutputMessage, Policy } from './types.ts';
|
||||||
|
|
||||||
type PolicyTuple<Opts = any> = [policy: Policy<Opts>, opts?: Opts];
|
type PolicyTuple<Opts = unknown> = [policy: Policy<Opts>, opts?: Opts];
|
||||||
|
|
||||||
|
// https://stackoverflow.com/a/75806165
|
||||||
|
// https://stackoverflow.com/a/54608401
|
||||||
type PolicyTuplesRest<T extends PolicyTuple[]> = {
|
type PolicyTuplesRest<T extends PolicyTuple[]> = {
|
||||||
[K in keyof T]: PolicyTuple<T[K]>
|
[K in keyof T]: PolicyTuple<T[K]> | Policy<T[K]>
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Processes messages through multiple policies, bailing early on rejection. */
|
/** Processes messages through multiple policies, bailing early on rejection. */
|
||||||
async function pipeline<P extends any[]>(msg: InputMessage, policies: [...PolicyTuplesRest<P>]): Promise<OutputMessage> {
|
async function pipeline<P extends any[]>(msg: InputMessage, policies: [...PolicyTuplesRest<P>]): Promise<OutputMessage> {
|
||||||
for (const tuple of policies) {
|
for (const item of policies) {
|
||||||
const [policy, opts] = tuple;
|
const [policy, opts] = toTuple(item);
|
||||||
const result = await policy(msg, opts);
|
const result = await policy(msg, opts);
|
||||||
if (result.action !== 'accept') {
|
if (result.action !== 'accept') {
|
||||||
return result;
|
return result;
|
||||||
@ -23,4 +25,9 @@ async function pipeline<P extends any[]>(msg: InputMessage, policies: [...Policy
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Coerce item into a tuple if it isn't already. */
|
||||||
|
function toTuple<T>(item: PolicyTuple<T> | Policy<T>): PolicyTuple<T> {
|
||||||
|
return typeof item === 'function' ? [item] : item;
|
||||||
|
}
|
||||||
|
|
||||||
export default pipeline;
|
export default pipeline;
|
||||||
|
Loading…
Reference in New Issue
Block a user