|
| 1 | +import { NgModule, APP_BOOTSTRAP_LISTENER, ApplicationRef } from '@angular/core' |
| 2 | +import { EnvironmentService, IBaseConfig } from './environment.service' |
| 3 | +import { ENV_CONFIG, ENV_CONFIG_TS_KEY } from './common' |
| 4 | +import { TransferState } from '@angular/platform-browser' |
| 5 | +import { filter, first, take } from 'rxjs/operators' |
| 6 | +import { REQUEST } from '@nguniversal/express-engine/tokens' |
| 7 | + |
| 8 | +function getConfigFromProcess() { |
| 9 | + return JSON.parse(process.env.FUSING_ANGULAR || '{}') |
| 10 | +} |
| 11 | + |
| 12 | +export function serverEnvConfigFactory() { |
| 13 | + return getConfigFromProcess() |
| 14 | +} |
| 15 | + |
| 16 | +// IF ENV CONTAINS SERVER_, remove from object |
| 17 | +function removeServerSpecific( |
| 18 | + obj: { readonly [key: string]: string }, |
| 19 | + filterKey = 'SERVER_' |
| 20 | +) { |
| 21 | + return Object.keys(obj) |
| 22 | + .filter(key => !key.includes(filterKey)) |
| 23 | + .reduce((acc, curr) => { |
| 24 | + return { |
| 25 | + ...acc, |
| 26 | + [curr]: obj[curr] |
| 27 | + } |
| 28 | + }, {}) |
| 29 | +} |
| 30 | + |
| 31 | +export function onBootstrap( |
| 32 | + appRef: ApplicationRef, |
| 33 | + transferState: TransferState, |
| 34 | + req: any |
| 35 | +) { |
| 36 | + return () => { |
| 37 | + appRef.isStable |
| 38 | + .pipe( |
| 39 | + filter(Boolean), |
| 40 | + first(), |
| 41 | + take(1) |
| 42 | + ) |
| 43 | + .subscribe(() => { |
| 44 | + transferState.set<IBaseConfig>( |
| 45 | + ENV_CONFIG_TS_KEY, |
| 46 | + removeServerSpecific(getConfigFromProcess()) |
| 47 | + ) |
| 48 | + }) |
| 49 | + } |
| 50 | +} |
| 51 | + |
| 52 | +// tslint:disable-next-line:no-class |
| 53 | +@NgModule({ |
| 54 | + providers: [ |
| 55 | + EnvironmentService, |
| 56 | + { provide: ENV_CONFIG, useFactory: serverEnvConfigFactory }, |
| 57 | + { |
| 58 | + provide: APP_BOOTSTRAP_LISTENER, |
| 59 | + useFactory: onBootstrap, |
| 60 | + deps: [ApplicationRef, TransferState, REQUEST], |
| 61 | + multi: true |
| 62 | + } |
| 63 | + ] |
| 64 | +}) |
| 65 | +export class EnvironmentServerModule {} |
0 commit comments