Build setting some configs. Configs used by server.

This commit is contained in:
William Welling
2017-03-24 20:54:24 -05:00
parent 9b23393121
commit 2974d8aab1
17 changed files with 103 additions and 95 deletions

View File

@@ -1,5 +1,4 @@
module.exports = { module.exports = {
"production": false,
// The REST API Location. // The REST API Location.
"rest": { "rest": {
// NOTE: Space is capitalized because 'namespace' is a reserved string in TypeScript // NOTE: Space is capitalized because 'namespace' is a reserved string in TypeScript
@@ -8,7 +7,7 @@ module.exports = {
"address": "localhost", "address": "localhost",
"port": 3000 "port": 3000
}, },
// Path and Port in use for this Angular2 UI // Protocol, path and port in use for this Angular2 UI
"ui": { "ui": {
"nameSpace": "/", "nameSpace": "/",
"protocol": "http", "protocol": "http",
@@ -17,11 +16,10 @@ module.exports = {
}, },
"cache": { "cache": {
// how long should objects be cached for by default // how long should objects be cached for by default
"msToLive": 15 * 60 * 1000, //15 minutes "msToLive": 1 * 60 * 1000, // 1 minute
}, },
"universal": { "universal": {
//on the client: start with the state on the server // universal settings
"shouldRehydrate": true,
"preboot": true, "preboot": true,
"async": true "async": true
} }

View File

@@ -6,8 +6,10 @@
<div class="container-fluid"> <div class="container-fluid">
<p>{{ 'example.with.data' | translate:data }}</p> <p>{{ 'example.with.data' | translate:data }}</p>
<p>{{ example }}</p> <p>{{ example }}</p>
<h2 *ngIf="!env" style="color:green">development</h2> <h2 [ngClass]="{ 'red': EnvConfig.production, 'green': !EnvConfig.production }">
<h2 *ngIf="env" style="color:red">production</h2> <span *ngIf="!EnvConfig.production">development</span>
<span *ngIf="EnvConfig.production">production</span>
</h2>
<router-outlet></router-outlet> <router-outlet></router-outlet>
</div> </div>
</main> </main>

View File

@@ -16,3 +16,11 @@
.main-content { .main-content {
flex: 1 0 auto; flex: 1 0 auto;
} }
h2.red {
color: red;
}
h2.green {
color: green;
}

View File

@@ -21,7 +21,7 @@ import { HostWindowState } from "./shared/host-window.reducer";
import { HostWindowResizeAction } from "./shared/host-window.actions"; import { HostWindowResizeAction } from "./shared/host-window.actions";
import { MockTranslateLoader } from "./shared/testing/mock-translate-loader"; import { MockTranslateLoader } from "./shared/testing/mock-translate-loader";
import { GLOBAL_CONFIG, config } from '../config'; import { GLOBAL_CONFIG, EnvConfig } from '../config';
let comp: AppComponent; let comp: AppComponent;
let fixture: ComponentFixture<AppComponent>; let fixture: ComponentFixture<AppComponent>;
@@ -39,7 +39,7 @@ describe('App component', () => {
})], })],
declarations: [AppComponent], // declare the test component declarations: [AppComponent], // declare the test component
providers: [ providers: [
{ provide: GLOBAL_CONFIG, useValue: config }, { provide: GLOBAL_CONFIG, useValue: EnvConfig },
AppComponent AppComponent
], ],
schemas: [CUSTOM_ELEMENTS_SCHEMA] schemas: [CUSTOM_ELEMENTS_SCHEMA]

View File

@@ -30,14 +30,8 @@ export class AppComponent implements OnDestroy, OnInit {
recipient: 'World' recipient: 'World'
}; };
env: string = this.config.production;
styles = {
color: 'red'
};
constructor( constructor(
@Inject(GLOBAL_CONFIG) private config: GlobalConfig, @Inject(GLOBAL_CONFIG) public EnvConfig: GlobalConfig,
private translate: TranslateService, private translate: TranslateService,
private store: Store<HostWindowState> private store: Store<HostWindowState>
) { ) {
@@ -45,8 +39,6 @@ export class AppComponent implements OnDestroy, OnInit {
translate.setDefaultLang('en'); translate.setDefaultLang('en');
// the lang to use, if the lang isn't available, it will use the current loader to get them // the lang to use, if the lang isn't available, it will use the current loader to get them
translate.use('en'); translate.use('en');
console.log(this.config);
} }
ngOnInit() { ngOnInit() {

View File

@@ -14,13 +14,13 @@ import { GLOBAL_CONFIG, GlobalConfig } from '../../../config';
@Injectable() @Injectable()
export class CollectionDataEffects extends DataEffects<Collection> { export class CollectionDataEffects extends DataEffects<Collection> {
constructor( constructor(
@Inject(GLOBAL_CONFIG) config: GlobalConfig, @Inject(GLOBAL_CONFIG) EnvConfig: GlobalConfig,
actions$: Actions, actions$: Actions,
restApi: DSpaceRESTv2Service, restApi: DSpaceRESTv2Service,
cache: ObjectCacheService, cache: ObjectCacheService,
dataService: CollectionDataService dataService: CollectionDataService
) { ) {
super(config, actions$, restApi, cache, dataService); super(EnvConfig, actions$, restApi, cache, dataService);
} }
protected getFindAllEndpoint(action: RequestCacheFindAllAction): string { protected getFindAllEndpoint(action: RequestCacheFindAllAction): string {

View File

@@ -14,13 +14,13 @@ import { GLOBAL_CONFIG, GlobalConfig } from '../../../config';
@Injectable() @Injectable()
export class ItemDataEffects extends DataEffects<Item> { export class ItemDataEffects extends DataEffects<Item> {
constructor( constructor(
@Inject(GLOBAL_CONFIG) config: GlobalConfig, @Inject(GLOBAL_CONFIG) EnvConfig: GlobalConfig,
actions$: Actions, actions$: Actions,
restApi: DSpaceRESTv2Service, restApi: DSpaceRESTv2Service,
cache: ObjectCacheService, cache: ObjectCacheService,
dataService: ItemDataService dataService: ItemDataService
) { ) {
super(config, actions$, restApi, cache, dataService); super(EnvConfig, actions$, restApi, cache, dataService);
} }
protected getFindAllEndpoint(action: RequestCacheFindAllAction): string { protected getFindAllEndpoint(action: RequestCacheFindAllAction): string {

View File

@@ -10,7 +10,7 @@ import { GLOBAL_CONFIG, GlobalConfig } from '../../../config';
*/ */
@Injectable() @Injectable()
export class DSpaceRESTv2Service { export class DSpaceRESTv2Service {
constructor(private http: Http, @Inject(GLOBAL_CONFIG) private config: GlobalConfig) { constructor(private http: Http, @Inject(GLOBAL_CONFIG) private EnvConfig: GlobalConfig) {
} }
@@ -25,7 +25,7 @@ export class DSpaceRESTv2Service {
* An Observablse<string> containing the response from the server * An Observablse<string> containing the response from the server
*/ */
get(relativeURL: string, options?: RequestOptionsArgs): Observable<string> { get(relativeURL: string, options?: RequestOptionsArgs): Observable<string> {
return this.http.get(new RESTURLCombiner(this.config, relativeURL).toString(), options) return this.http.get(new RESTURLCombiner(this.EnvConfig, relativeURL).toString(), options)
.map(res => res.json()) .map(res => res.json())
.catch(err => { .catch(err => {
console.log('Error: ', err); console.log('Error: ', err);

View File

@@ -9,7 +9,7 @@ import { GlobalConfig } from '../../../config';
* TODO write tests once GlobalConfig becomes injectable * TODO write tests once GlobalConfig becomes injectable
*/ */
export class RESTURLCombiner extends URLCombiner { export class RESTURLCombiner extends URLCombiner {
constructor(config: GlobalConfig, ...parts: Array<string>) { constructor(EnvConfig: GlobalConfig, ...parts: Array<string>) {
super(config.rest.baseURL, config.rest.nameSpace, ...parts); super(EnvConfig.rest.baseUrl, EnvConfig.rest.nameSpace, ...parts);
} }
} }

View File

@@ -1,9 +1,9 @@
<div class="page-not-found"> <div class="page-not-found">
<h1>404</h1> <h1>404</h1>
<h2><small>{{"404.page-not-found" | translate}}</small></h2> <h2><small>{{"404.page-not-found" | translate}}</small></h2>
<br> <br/>
<p>{{"404.help" | translate}}</p> <p>{{"404.help" | translate}}</p>
<br> <br/>
<p class="text-center"> <p class="text-center">
<a routerLink="/home" class="btn btn-primary">{{"404.link.home-page" | translate}}</a> <a routerLink="/home" class="btn btn-primary">{{"404.link.home-page" | translate}}</a>
</p> </p>

View File

@@ -1,6 +1,5 @@
import { Component } from '@angular/core'; import { Component } from '@angular/core';
@Component({ @Component({
selector: 'ds-pagenotfound', selector: 'ds-pagenotfound',
styleUrls: ['./pagenotfound.component.css'], styleUrls: ['./pagenotfound.component.css'],

View File

@@ -1,48 +1,16 @@
// Look in ./config folder for config // Look in ./config folder for config
import { OpaqueToken } from '@angular/core'; import { OpaqueToken } from '@angular/core';
import * as path from 'path';
let configContext = require.context("../config", false, /js$/);
let EnvConfig: any = {};
let EnvConfigFile: string;
let DefaultConfig: any = {};
try {
DefaultConfig = configContext('./environment.default.js');
} catch (e) {
throw new Error(`Cannot find file "${path.resolve('config', './environment.default.js')}"`);
}
switch (process.env.NODE_ENV) {
case 'prod':
case 'production':
EnvConfigFile = './environment.prod.js';
break;
case 'dev':
case 'development':
default:
EnvConfigFile = './environment.dev.js';
}
try {
EnvConfig = configContext(EnvConfigFile);
} catch (e) {
EnvConfig = {};
}
const GLOBAL_CONFIG = new OpaqueToken('config');
interface ServerConfig { interface ServerConfig {
"nameSpace": string, "nameSpace": string,
"protocol": string, "protocol": string,
"address": string, "address": string,
"port": number, "port": number,
"baseURL": string "baseUrl": string
} }
interface GlobalConfig { interface GlobalConfig {
"production": string, "production": boolean,
"rest": ServerConfig, "rest": ServerConfig,
"ui": ServerConfig, "ui": ServerConfig,
"cache": { "cache": {
@@ -55,16 +23,55 @@ interface GlobalConfig {
} }
} }
const config: GlobalConfig = <GlobalConfig>Object.assign(DefaultConfig, EnvConfig); const GLOBAL_CONFIG = new OpaqueToken('config');
function buildURL(server: ServerConfig) { let configContext = require.context("../config", false, /js$/);
return [server.protocol, '://', server.address, (server.port !== 80) ? ':' + server.port : ''].join('');
let EnvConfig: GlobalConfig;
let EnvConfigFile: string;
let production: boolean = false;
switch (process.env.NODE_ENV) {
case 'prod':
case 'production':
production = true;
EnvConfigFile = './environment.prod.js';
break;
case 'dev':
case 'development':
EnvConfigFile = './environment.dev.js';
break;
case 'test':
EnvConfigFile = './environment.test.js';
break;
default:
console.warn('Environment file not specified. Using default.')
} }
for (let key in config) { try {
if (config[key].protocol && config[key].address && config[key].port) { EnvConfig = configContext('./environment.default.js');
config[key].baseURL = buildURL(config[key]); } catch (e) {
throw new Error("Cannot find file ./environment.default.js");
}
// if EnvConfigFile set try to get configs
if(EnvConfigFile) {
try {
EnvConfig = <GlobalConfig> Object.assign(EnvConfig, configContext(EnvConfigFile));
} catch (e) {
console.warn("Cannot find file " + EnvConfigFile);
} }
} }
export { GLOBAL_CONFIG, GlobalConfig, config } // set base url if propery is object with protocol, address, and port. i.e. ServerConfig
for (let key in EnvConfig) {
if (EnvConfig[key].protocol && EnvConfig[key].address && EnvConfig[key].port) {
EnvConfig[key].baseUrl = [EnvConfig[key].protocol, '://', EnvConfig[key].address, (EnvConfig[key].port !== 80) ? ':' + EnvConfig[key].port : ''].join('');
}
}
// set config for running in production
EnvConfig.production = production;
export { GLOBAL_CONFIG, GlobalConfig, EnvConfig }

View File

@@ -23,7 +23,7 @@ import { effects } from '../../app/app.effects';
import { Meta } from '../angular2-meta'; import { Meta } from '../angular2-meta';
import { RehydrateStoreAction } from "../../app/store.actions"; import { RehydrateStoreAction } from "../../app/store.actions";
import { GLOBAL_CONFIG, config } from '../../config'; import { GLOBAL_CONFIG, EnvConfig } from '../../config';
// import * as LRU from 'modern-lru'; // import * as LRU from 'modern-lru';
@@ -72,7 +72,8 @@ export const UNIVERSAL_KEY = 'UNIVERSAL_CACHE';
effects effects
], ],
providers: [ providers: [
{ provide: GLOBAL_CONFIG, useValue: config }, { provide: GLOBAL_CONFIG, useValue: EnvConfig },
{ provide: 'isBrowser', useValue: isBrowser }, { provide: 'isBrowser', useValue: isBrowser },
{ provide: 'isNode', useValue: isNode }, { provide: 'isNode', useValue: isNode },

View File

@@ -21,7 +21,7 @@ import { effects } from '../../app/app.effects';
// see https://github.com/angular/angular/pull/12322 // see https://github.com/angular/angular/pull/12322
import { Meta } from '../angular2-meta'; import { Meta } from '../angular2-meta';
import { GLOBAL_CONFIG, config } from '../../config'; import { GLOBAL_CONFIG, EnvConfig } from '../../config';
export function createTranslateLoader(http: Http) { export function createTranslateLoader(http: Http) {
return new TranslateStaticLoader(http, './assets/i18n', '.json'); return new TranslateStaticLoader(http, './assets/i18n', '.json');
@@ -63,8 +63,8 @@ export const UNIVERSAL_KEY = 'UNIVERSAL_CACHE';
effects effects
], ],
providers: [ providers: [
{ provide: GLOBAL_CONFIG, useValue: config }, { provide: GLOBAL_CONFIG, useValue: EnvConfig },
{ provide: 'res', useFactory: getResponse },
{ provide: 'isBrowser', useValue: isBrowser }, { provide: 'isBrowser', useValue: isBrowser },
{ provide: 'isNode', useValue: isNode }, { provide: 'isNode', useValue: isNode },

View File

@@ -25,7 +25,7 @@ import { MainModuleNgFactory } from './platform/modules/node.module.ngfactory';
// Routes // Routes
import { routes } from './server.routes'; import { routes } from './server.routes';
import { config } from './config'; import { EnvConfig } from './config';
// enable prod for faster renders // enable prod for faster renders
enableProdMode(); enableProdMode();
@@ -44,8 +44,9 @@ app.engine('.html', createEngine({
// stateless providers only since it's shared // stateless providers only since it's shared
] ]
})); }));
app.set('port', process.env.PORT || 3000);
app.set('address', process.env.ADDRESS || '127.0.0.1'); app.set('port', process.env.PORT || EnvConfig.ui.port || 3000);
app.set('address', process.env.ADDRESS || EnvConfig.ui.address || '127.0.0.1');
app.set('views', __dirname); app.set('views', __dirname);
app.set('view engine', 'html'); app.set('view engine', 'html');
app.set('json spaces', 2); app.set('json spaces', 2);
@@ -66,13 +67,13 @@ function cacheControl(req, res, next) {
res.header('Cache-Control', 'max-age=60'); res.header('Cache-Control', 'max-age=60');
next(); next();
} }
// Serve static files // Serve static files
app.use('/assets', cacheControl, express.static(path.join(__dirname, 'assets'), { maxAge: 30 })); app.use('/assets', cacheControl, express.static(path.join(__dirname, 'assets'), { maxAge: 30 }));
app.use('/styles', cacheControl, express.static(path.join(__dirname, 'styles'), { maxAge: 30 })); app.use('/styles', cacheControl, express.static(path.join(__dirname, 'styles'), { maxAge: 30 }));
app.use(cacheControl, express.static(path.join(ROOT, 'dist/client'), { index: false })); app.use(cacheControl, express.static(path.join(ROOT, 'dist/client'), { index: false }));
//
///////////////////////// /////////////////////////
// ** Example API // ** Example API
// Notice API should be in a separate process // Notice API should be in a separate process
@@ -95,11 +96,11 @@ function ngApp(req, res) {
res, res,
// use this to determine what part of your app is slow only in development // use this to determine what part of your app is slow only in development
// time: true, // time: true,
async: true, async: EnvConfig.universal.async,
preboot: true, preboot: EnvConfig.universal.preboot,
baseUrl: '/', baseUrl: EnvConfig.ui.nameSpace,
requestUrl: req.originalUrl, requestUrl: req.originalUrl,
originUrl: `http://${app.get('address')}:${app.get('port')}` originUrl: EnvConfig.ui.baseUrl
}); });
}); });
@@ -114,7 +115,6 @@ routes.forEach(route => {
app.get(`/${route}/*`, ngApp); app.get(`/${route}/*`, ngApp);
}); });
app.get('*', function(req, res) { app.get('*', function(req, res) {
res.setHeader('Content-Type', 'application/json'); res.setHeader('Content-Type', 'application/json');
var pojo = { status: 404, message: 'No Content' }; var pojo = { status: 404, message: 'No Content' };
@@ -124,5 +124,5 @@ app.get('*', function(req, res) {
// Server // Server
let server = app.listen(app.get('port'), app.get('address'), () => { let server = app.listen(app.get('port'), app.get('address'), () => {
console.log(`Listening on: http://${server.address().address}:${server.address().port}`); console.log(`Listening on: ${EnvConfig.ui.protocol}://${server.address().address}:${server.address().port}`);
}); });

View File

@@ -24,7 +24,7 @@ import { MainModule } from './platform/modules/node.module';
// Routes // Routes
import { routes } from './server.routes'; import { routes } from './server.routes';
import { config } from './config'; import { EnvConfig } from './config';
// enable prod for faster renders // enable prod for faster renders
enableProdMode(); enableProdMode();
@@ -42,8 +42,9 @@ app.engine('.html', createEngine({
// stateless providers only since it's shared // stateless providers only since it's shared
] ]
})); }));
app.set('port', process.env.PORT || 3000);
app.set('address', process.env.ADDRESS || '127.0.0.1'); app.set('port', process.env.PORT || EnvConfig.ui.port || 3000);
app.set('address', process.env.ADDRESS || EnvConfig.ui.address || '127.0.0.1');
app.set('views', __dirname); app.set('views', __dirname);
app.set('view engine', 'html'); app.set('view engine', 'html');
app.set('json spaces', 2); app.set('json spaces', 2);
@@ -59,13 +60,13 @@ function cacheControl(req, res, next) {
res.header('Cache-Control', 'max-age=60'); res.header('Cache-Control', 'max-age=60');
next(); next();
} }
// Serve static files // Serve static files
app.use('/assets', cacheControl, express.static(path.join(__dirname, 'assets'), { maxAge: 30 })); app.use('/assets', cacheControl, express.static(path.join(__dirname, 'assets'), { maxAge: 30 }));
app.use('/styles', cacheControl, express.static(path.join(__dirname, 'styles'), { maxAge: 30 })); app.use('/styles', cacheControl, express.static(path.join(__dirname, 'styles'), { maxAge: 30 }));
app.use(cacheControl, express.static(path.join(ROOT, 'dist/client'), { index: false })); app.use(cacheControl, express.static(path.join(ROOT, 'dist/client'), { index: false }));
//
///////////////////////// /////////////////////////
// ** Example API // ** Example API
// Notice API should be in aseparate process // Notice API should be in aseparate process
@@ -87,11 +88,11 @@ function ngApp(req, res) {
req, req,
res, res,
// time: true, // use this to determine what part of your app is slow only in development // time: true, // use this to determine what part of your app is slow only in development
async: true, async: EnvConfig.universal.async,
preboot: true, preboot: EnvConfig.universal.preboot,
baseUrl: '/', baseUrl: EnvConfig.ui.nameSpace,
requestUrl: req.originalUrl, requestUrl: req.originalUrl,
originUrl: `http://${app.get('address')}:${app.get('port')}` originUrl: EnvConfig.ui.baseUrl
}); });
}); });
@@ -115,5 +116,5 @@ app.get('*', function(req, res) {
// Server // Server
let server = app.listen(app.get('port'), app.get('address'), () => { let server = app.listen(app.get('port'), app.get('address'), () => {
console.log(`Listening on: http://${server.address().address}:${server.address().port}`); console.log(`Listening on: ${EnvConfig.ui.protocol}://${server.address().address}:${server.address().port}`);
}); });