UNPKG

1.8 kBPlain TextView Raw
1// Dependencies:
2import { IneedaInterceptor, IneedaInterceptorFunction, IneedaInterceptorToken } from './ineeda-types';
3
4// Constants:
5let INTERCEPTORS: Array<IneedaInterceptorFunction<any, keyof any>> = [];
6let INTERCEPTORS_WITH_TOKEN: Map<IneedaInterceptorToken, Array<IneedaInterceptorFunction<any, keyof any>>> = new Map();
7
8export function getGlobalInterceptors <T> (): Array<IneedaInterceptorFunction<T, keyof T>> {
9 return <Array<IneedaInterceptorFunction<T, keyof T>>>INTERCEPTORS;
10}
11
12export 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
29export function getInterceptorsForToken <T> (token: IneedaInterceptorToken): Array<IneedaInterceptorFunction<T, keyof T>> {
30 return <Array<IneedaInterceptorFunction<T, keyof T>>>INTERCEPTORS_WITH_TOKEN.get(token);
31}
32
33export function resetInterceptors (): void {
34 INTERCEPTORS.length = 0;
35 INTERCEPTORS_WITH_TOKEN.clear();
36}
37
38export function setInterceptors <T> (interceptor: IneedaInterceptor<T>): void {
39 INTERCEPTORS = INTERCEPTORS.concat(getInterceptors(interceptor));
40}
41
42export function setInterceptorsForToken <T> (token: IneedaInterceptorToken, interceptor: IneedaInterceptor<T>): void {
43 INTERCEPTORS_WITH_TOKEN.set(token, getInterceptors(interceptor));
44}