1 |
|
2 | import { IneedaInterceptor, IneedaInterceptorFunction, IneedaInterceptorToken } from './ineeda-types';
|
3 |
|
4 |
|
5 | let INTERCEPTORS: Array<IneedaInterceptorFunction<any, keyof any>> = [];
|
6 | let INTERCEPTORS_WITH_TOKEN: Map<IneedaInterceptorToken, Array<IneedaInterceptorFunction<any, keyof any>>> = new Map();
|
7 |
|
8 | export function getGlobalInterceptors <T> (): Array<IneedaInterceptorFunction<T, keyof T>> {
|
9 | return <Array<IneedaInterceptorFunction<T, keyof T>>>INTERCEPTORS;
|
10 | }
|
11 |
|
12 | export function getInterceptors <T> (interceptor: IneedaInterceptor<T>): Array<IneedaInterceptorFunction<T, keyof T>> {
|
13 | let interceptors: Array<IneedaInterceptorFunction<T, keyof T>> = [];
|
14 | if (interceptor instanceof Function) {
|
15 | interceptors.push(interceptor);
|
16 | } else {
|
17 | Object.keys(interceptor).forEach((interceptorKey: keyof T) => {
|
18 | interceptors.push((value, key) => {
|
19 | if (key === interceptorKey) {
|
20 | return interceptor[interceptorKey];
|
21 | }
|
22 | return value;
|
23 | });
|
24 | });
|
25 | }
|
26 | return interceptors;
|
27 | }
|
28 |
|
29 | export function getInterceptorsForToken <T> (token: IneedaInterceptorToken): Array<IneedaInterceptorFunction<T, keyof T>> {
|
30 | return <Array<IneedaInterceptorFunction<T, keyof T>>>INTERCEPTORS_WITH_TOKEN.get(token);
|
31 | }
|
32 |
|
33 | export function resetInterceptors (): void {
|
34 | INTERCEPTORS.length = 0;
|
35 | INTERCEPTORS_WITH_TOKEN.clear();
|
36 | }
|
37 |
|
38 | export function setInterceptors <T> (interceptor: IneedaInterceptor<T>): void {
|
39 | INTERCEPTORS = INTERCEPTORS.concat(getInterceptors(interceptor));
|
40 | }
|
41 |
|
42 | export function setInterceptorsForToken <T> (token: IneedaInterceptorToken, interceptor: IneedaInterceptor<T>): void {
|
43 | INTERCEPTORS_WITH_TOKEN.set(token, getInterceptors(interceptor));
|
44 | }
|