strfry-policies/src/pipeline.ts

34 lines
999 B
TypeScript
Raw Normal View History

import { InputMessage, OutputMessage, Policy } from './types.ts';
2023-03-24 19:36:11 +00:00
2023-03-25 01:06:03 +00:00
type PolicyTuple<Opts = unknown> = [policy: Policy<Opts>, opts?: Opts];
2023-03-25 00:55:58 +00:00
2023-03-25 01:06:03 +00:00
// https://stackoverflow.com/a/75806165
// https://stackoverflow.com/a/54608401
2023-03-25 00:55:58 +00:00
type PolicyTuplesRest<T extends PolicyTuple[]> = {
2023-03-25 01:06:03 +00:00
[K in keyof T]: PolicyTuple<T[K]> | Policy<T[K]>
2023-03-25 00:55:58 +00:00
}
/** Processes messages through multiple policies, bailing early on rejection. */
2023-03-25 00:55:58 +00:00
async function pipeline<P extends any[]>(msg: InputMessage, policies: [...PolicyTuplesRest<P>]): Promise<OutputMessage> {
2023-03-25 01:06:03 +00:00
for (const item of policies) {
const [policy, opts] = toTuple(item);
2023-03-25 00:55:58 +00:00
const result = await policy(msg, opts);
if (result.action !== 'accept') {
return result;
}
}
return {
id: msg.event.id,
action: 'accept',
msg: '',
};
}
2023-03-25 01:06:03 +00:00
/** 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;