-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
splitLink.ts
30 lines (29 loc) · 1.08 KB
/
splitLink.ts
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
import { observable } from '@trpc/server/observable';
import type { AnyRouter } from '@trpc/server/unstable-core-do-not-import';
import { createChain } from './internals/createChain';
import type { Operation, TRPCLink } from './types';
function asArray<TType>(value: TType | TType[]) {
return Array.isArray(value) ? value : [value];
}
export function splitLink<TRouter extends AnyRouter = AnyRouter>(opts: {
condition: (op: Operation) => boolean;
/**
* The link to execute next if the test function returns `true`.
*/
true: TRPCLink<TRouter> | TRPCLink<TRouter>[];
/**
* The link to execute next if the test function returns `false`.
*/
false: TRPCLink<TRouter> | TRPCLink<TRouter>[];
}): TRPCLink<TRouter> {
return (runtime) => {
const yes = asArray(opts.true).map((link) => link(runtime));
const no = asArray(opts.false).map((link) => link(runtime));
return (props) => {
return observable((observer) => {
const links = opts.condition(props.op) ? yes : no;
return createChain({ op: props.op, links }).subscribe(observer);
});
};
};
}