forked from ngrx/router
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.ts
51 lines (41 loc) · 1.29 KB
/
middleware.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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
/**
* The router exposes a number of middleware entrypoints. These are utilities
* for quickly creating injector-friendly middleware.
*/
import { Observable } from 'rxjs/Observable';
import { OpaqueToken, Provider, provide, Injector } from 'angular2/core';
import { compose, createFactoryProvider } from './util';
export interface Middleware {
(input$: Observable<any>): Observable<any>;
}
export const identity: Middleware = t => t;
export function createMiddleware(
useFactory: (...deps: any[]) => Middleware, deps?: any[]
): Provider {
return provide(new OpaqueToken('@ngrx/store middleware'), {
deps,
useFactory
});
}
export function provideMiddlewareForToken(token) {
function isProvider(t: any): t is Provider {
return t instanceof Provider;
}
return function(..._middleware: Array<Middleware | Provider>): Provider[] {
const provider = provide(token, {
multi: true,
deps: [ Injector ],
useFactory(injector: Injector) {
const middleware = _middleware.map(m => {
if (isProvider(m)) {
return injector.get(m.token);
}
return m;
});
return compose(...middleware);
}
});
const providers = _middleware.filter(isProvider) as Provider[];
return [ ...providers, provider ];
};
}