I am trying to manage some logic by using .env varibles but I dont how what I am doing wrong and a can get the variables loaded inside my services.
Here is my App.module.ts:
...
import { ConfigModule } from '#nestjs/config';
import configuration from './config/configuration';
...
#Module({
imports: [
ConfigModule.forRoot({
load: [configuration],
validationSchema: JoiValidationSchema,
isGlobal: true,
}),
...
],
...
})
export class AppModule {}
Here is the configuration file:
export default () => ({
environment: process.env.NODE_ENV || 'dev',
port: process.env.PORT || 5000,
postgresPassword: process.env.POSTGRES_PASSWORD,
postgresUsername: process.env.POSTGRES_USERNAME,
postgresDbName: process.env.POSTGRES_NAME,
postgresHost: process.env.POSTGRES_HOST,
postgresPort: parseInt(process.env.POSTGRES_PORT, 10),
defaultLimit: parseInt(process.env.DEFAULT_LIMIT, 10) || 10,
});
When I print the variables in my ProductServices contructor it works good
export class ProductsService {
private readonly logger = new Logger('ProductsServices');
constructor(
...
private readonly configService: ConfigService,
) {
console.log(this.defaultLimit); // 10
console.log(this.environment); // 'dev'
}
defaultLimit = this.configService.get<number>('defaultLimit');
environment = this.configService.get<string>('environment');
But when I trying to using in one of my ProductService methods it is undefined:
async removeAll() {
console.log(this.environment); // undefined
try {
if (this.environment !== 'dev') {
throw new UnauthorizedException();
}
...
} catch (error) {
...
}
}
Any help will be appreciated
I need get the enviroment to manage some seed logic
Related
Short form question:
We are trying to access the express-http-context in a dependent logger module of our main NodeJS service. However, we are getting it as undefined.
Context:
We are trying to tag all our logs with a requestId for each unique request in NodeJS. We have a logger module that wraps winston logger. This logger module is a separate package and is used across all our different NodeJs (Express) services.
Our winston logger wrapper file in our cf-logger-module is as follows:
import { omit } from 'lodash';
import { Logger, createLogger, format, transports, LeveledLogMethod } from 'winston';
import httpcontext from 'express-http-context';
import Sentry from 'winston-sentry-log';
import { ILoggerConfig } from '../interfaces/ILoggerConfig';
import { LevelCodes } from '../constants/LoggingLevels';
import ILoggerAdapter from '../interfaces/ILoggerAdapter';
import LoggerConfiguration from '../LoggerConfiguration';
export default class WinstonLogger implements ILoggerAdapter {
private readonly _logger: Logger;
private _config: ILoggerConfig;
private _moduleName: string;
private _loggingMethods: { [prop: number]: LeveledLogMethod };
public static createAdapter(moduleName: string, config: LoggerConfiguration): ILoggerAdapter {
return new WinstonLogger(moduleName, config);
}
public constructor(moduleName: string, loggerConfiguration: LoggerConfiguration) {
this._config = loggerConfiguration.config;
this._moduleName = moduleName;
const sentryOptions = {
config: {
dsn: 'https://b71e24c577604eab977dcf18720f1d5a#o1185085.ingest.sentry.io/6468703',
},
level: 'info',
};
this._logger = createLogger({
levels: LevelCodes,
transports: [new transports.Console({ level: this._config.logging.level }), new Sentry(sentryOptions)],
format: format.combine(
format.timestamp({ format: this._config.logging.timestamp.format }),
format.errors({ stack: this._config.logging.errors.stack }),
format.simple(),
format.colorize(),
format.printf(({ level, message, timestamp, ...metadata }) => {
const module = metadata.module;
const method = `${metadata.methodName}()`;
metadata = omit(metadata, 'module');
metadata = omit(metadata, 'methodName');
// console.log('Logger http context', httpcontext.get('reqId'));
return `${timestamp} [${module}:${method}] [${level}]: ${message} ${JSON.stringify(metadata)}`;
}),
),
});
/* istanbul ignore next */
this._loggingMethods = {
[LevelCodes.debug]: this._logger?.debug.bind(this._logger),
[LevelCodes.error]: this._logger?.error.bind(this._logger),
[LevelCodes.http]: this._logger?.http.bind(this._logger),
[LevelCodes.info]: this._logger?.info.bind(this._logger),
[LevelCodes.silly]: this._logger?.silly.bind(this._logger),
[LevelCodes.verbose]: this._logger?.verbose.bind(this._logger),
[LevelCodes.warn]: this._logger?.warn.bind(this._logger),
};
}
public logMessage(level: number, message: string, metadata?: object, error?: Error): void {
this._loggingMethods[level](message, this.process(metadata, error));
}
private process(metadata?: object, error?: Error): object {
/** Extract Service Name */
console.log('Logger http context', httpcontext.get('reqId'));
Object.assign(metadata, {
module: `${this._config.service.name}.${this._moduleName}`,
});
/** Extract Error */
if (error !== undefined) {
Object.assign(error, metadata);
}
/** TODO: Sanitize and metadata */
return error || metadata;
}
}
As you can see we are trying to access the reqID set using express-http-context.
Our nodeJs apps package.json dependencies look like:
"dependencies": {
"#coverforce-platform/cf-logger-module": "^1.0.26",
....
"express-http-context": "^1.2.4",
"express-ruid": "^1.1.4",
},
The app.ts looks like:
private initializeMiddlewares() {
this.app.use(cors({ origin: AppConfig.getValues().SERVICE.ORIGIN }));
this.app.use(hpp());
this.app.use(helmet());
this.app.use(compression());
this.app.use(express.json());
this.app.use(express.urlencoded({ extended: true }));
this.app.use(cookieParser());
this.app.use(httpcontext.middleware);
this.app.use(ruid({ setInContext: true, attribute: 'reqId' }));
this.app.use(Sentry.Handlers.requestHandler() as express.RequestHandler);
this.app.use(Sentry.Handlers.errorHandler());
this.app.use(Sentry.Handlers.tracingHandler());
}
and the server.ts is:
import 'reflect-metadata';
import { Container } from 'typedi';
import { LoggerFactory, ILogger } from '#coverforce-platform/cf-logger-module';
import { AppConfig } from '#coverforce-platform/cf-config-module';
import { ErrorResponseMiddleware } from '#coverforce-platform/cf-error-module';
import { SchemaValidationMiddleware } from '#coverforce-platform/cf-schema-validation-module';
import { AccountsServiceSchema } from '#coverforce-platform/cf-common-api-model';
import { accountsDatabaseLoader } from './dependencyInjection/accountsDatabase.dependency';
import { App } from './app';
import { ERROR_RESPONSE_MIDDLEWARE, SCHEMA_VALIDATION_MIDDLEWARE } from './constants/dependencyInjection.constants';
main();
async function main() {
const logger: ILogger = initLogger();
await initAppConfig(logger);
initializeDependencyInjection();
const app: App = Container.get(App);
app.listen();
}
However, in the logger the console.log('Http Context', httpcontext.get('reqId') is always returning undefined for the reqId field in the httpcontext. If we do the same within any class in the main service we are able to retrieve the httpcontext's reqId. However, we are not able to access it in the dependent package/module.
I'm trying to use a service inside a decorator and this decorator is used over ServiceX function, which is called from some serviceY. However getting an error. Spent quite a long time with no success. Any help will be appreciated.
Error: Nest can't resolve dependencies of ServiceX. Please make sure that the "logger" property is available in the current context.
// myDecortor.ts
import { Inject } from '#nestjs/common';
import { LoggerService } from '../../logger/logger.service';
export function myDecorator(bubble = true) {
const injectLogger = Inject(LoggerService);
return (target: any, propertyKey: string, propertyDescriptor: PropertyDescriptor) => {
injectLogger(target, 'logger'); // This logger property is not accessible to ServiceX
//get original method
const originalMethod = propertyDescriptor.value;
//redefine descriptor value within own function block
propertyDescriptor.value = async function(...args: any[]) {
// something
};
};
}
importing LoggerModule in ServiceXModule
// serviceX.module.ts
import { LoggerModule } from '../../logger/logger.module';
/// .....
#Module({
imports: [LoggerModule],
providers: [serviceX],
exports: [ServiceX],
})
Using decortor over a method of ServiceX class.
// serviceX.service.ts
import { myDecorator } from '../logger/myDecorator';
#myDecorator()
async serviceXfunction() {
//some more stuff
}
Importing serviceX module in ServiceY
// serviceY.module.ts
import { ServiceXModule } from '../../logger/serviceX.module';
/// .....
#Module({
imports: [ServiceXModule],
providers: [serviceY],
exports: [ServiceY],
})
// serviceY.service.ts
import { ServiceX } from '../logger/serviceX.service';
constructor(private readonly serviceX: ServiceX){}
async serviceYfunction() {
await serviceX.serviceXfunction();
}
I'm trying to make angular 2 service with config file passed through constructor so i can read the config after it initializes and start other part of the code. I'm trying to make config file in app.module.ts and trough provider use factory to pass it down to my service but i have no luck, I've been stuck searching for google answers but i can't find the right solution. My code is bellow, i created config
app.module.ts
const config = new AuthServiceConfig([
{
id: FacebookLoginProvider.PROVIDER_ID,
provider: new FacebookLoginProvider(),
},
{
id: LinedinLoginProvider.PROVIDER_ID,
provider: new LinedinLoginProvider(),
},
]);
export function provideConfig() {
return config;
}
export function configFactory(config: AuthServiceConfig) {
return config;
}
providers: [
...
{ provide: AuthServiceConfig, useFactory: provideConfig },
{ provide: AuthProvider, useFactory: config },
],
auth.ts
export interface AuthServiceConfigItem {
id: string;
provider: Provider;
}
export class AuthServiceConfig {
providers: Map<string, Provider> = new Map<string, Provider>();
constructor(providers: AuthServiceConfigItem[]) {
for (let i = 0; i < providers.length; i++) {
let element = providers[i];
this.providers.set(element.id, element.provider);
}
}
}
#Injectable()
export class AuthProvider {
private static readonly ERR_LOGIN_PROVIDER_NOT_FOUND =
'Login provider not found';
providers: Map<string, Provider> = new Map<string, Provider>();
constructor(config) {
this.providers = config.providers;
console.log('Ovo su providersi u konstruktoru', this.providers);
}
I haven't tried dynamically change providers, but I used the Angular CLI environment files. Based on some flag from the environment file I would instantiate the proper service in the factory function.
Take a look at the app.module.ts and product.factory.ts here: https://github.com/Farata/angulartypescript/tree/master/code-samples/Angular6/chapter5/di-samples/src/app/factory
Below error shown when I ran ng test command.
Here is my service spec,
describe('BackendService', () => {
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
{
provide: Http, useFactory: (backend, options) => {
return new Http(backend, options);
},
deps: [MockBackend, BaseRequestOptions]
},
MockBackend,
BaseRequestOptions,
BackendService
]
});
});
it('should ...', inject([BackendService, MockBackend], (service: BackendService) => {
expect(service).toBeTruthy();
})
);
});
BackendService.ts looks like,
export class BackendService {
private baseUrl: string = 'https://foo-backend.appspot.com/_ah/api/default/v1';
constructor(private http: Http, baseName: string) {
this.baseUrl = this.baseUrl + baseName;
}
.....
}
It seems like extra parameter inside the BackendService class's constructor causes this problem..
How do you expect Angular to know what baseName is supposed to be? All constructor parameters need to be obtained from the Injector. And if there is no corresponding token for the parameter, then it can't be looked up.
You can add a token by doing
// somewhere in some file
import { OpaqueToken } from '#angular/core';
export const BASE_NAME_TOKEN = new OpaqueToken("app.base_name");
// in test class
import { BASE_NAME_TOKEN } from 'where-ever'
TestBed.configureTestingModule({
providers: [
BackendService,
{ provide: BASE_NAME_TOKEN, useValue: 'whatever-the-base-is' }
]
});
// in service constructor
import { Inject } from '#angular/core'
import { BASE_NAME_TOKEN } from 'where-ever'
constructor(http: Http, #Inject(BASE_NAME_TOKEN) baseName: string) {}
See Also:
Dependency Injection Tokens
What is the difference between #Inject vs constructor injection as normal parameter in Angular 2?
Is there a way to pass arguments rendered on the backend to angular2 bootstrap method? I want to set http header for all requests using BaseRequestOptions with value provided from the backend. My main.ts file looks like this:
import { bootstrap } from '#angular/platform-browser-dynamic';
import { AppComponent } from "./app.component.ts";
bootstrap(AppComponent);
I found how to pass this arguments to root component (https://stackoverflow.com/a/35553650/3455681), but i need it when I'm fireing bootstrap method... Any ideas?
edit:
webpack.config.js content:
module.exports = {
entry: {
app: "./Scripts/app/main.ts"
},
output: {
filename: "./Scripts/build/[name].js"
},
resolve: {
extensions: ["", ".ts", ".js"]
},
module: {
loaders: [
{
test: /\.ts$/,
loader: 'ts-loader'
}
]
}
};
update2
Plunker example
update AoT
To work with AoT the factory closure needs to be moved out
function loadContext(context: ContextService) {
return () => context.load();
}
#NgModule({
...
providers: [ ..., ContextService, { provide: APP_INITIALIZER, useFactory: loadContext, deps: [ContextService], multi: true } ],
See also https://github.com/angular/angular/issues/11262
update an RC.6 and 2.0.0 final example
function configServiceFactory (config: ConfigService) {
return () => config.load();
}
#NgModule({
declarations: [AppComponent],
imports: [BrowserModule,
routes,
FormsModule,
HttpModule],
providers: [AuthService,
Title,
appRoutingProviders,
ConfigService,
{ provide: APP_INITIALIZER,
useFactory: configServiceFactory
deps: [ConfigService],
multi: true }
],
bootstrap: [AppComponent]
})
export class AppModule { }
If there is no need to wait for the initialization to complete, the constructor of `class AppModule {} can also be used:
class AppModule {
constructor(/*inject required dependencies */) {...}
}
hint (cyclic dependency)
For example injecting the router can cause cyclic dependencies.
To work around, inject the Injector and get the dependency by
this.myDep = injector.get(MyDependency);
instead of injecting MyDependency directly like:
#Injectable()
export class ConfigService {
private router:Router;
constructor(/*private router:Router*/ injector:Injector) {
setTimeout(() => this.router = injector.get(Router));
}
}
update
This should work the same in RC.5 but instead add the provider to providers: [...] of the root module instead of bootstrap(...)
(not tested myself yet).
update
An interesting approach to do it entirely inside Angular is explained here https://github.com/angular/angular/issues/9047#issuecomment-224075188
You can use APP_INITIALIZER which will execute a function when the
app is initialized and delay what it provides if the function returns
a promise. This means the app can be initializing without quite so
much latency and you can also use the existing services and framework
features.
As an example, suppose you have a multi-tenanted solution where the
site info relies on the domain name it's being served from. This can
be [name].letterpress.com or a custom domain which is matched on the
full hostname. We can hide the fact that this is behind a promise by
using APP_INITIALIZER.
In bootstrap:
{provide: APP_INITIALIZER, useFactory: (sites:SitesService) => () => sites.load(), deps:[SitesService, HTTP_PROVIDERS], multi: true}),
sites.service.ts:
#Injectable()
export class SitesService {
public current:Site;
constructor(private http:Http, private config:Config) { }
load():Promise<Site> {
var url:string;
var pos = location.hostname.lastIndexOf(this.config.rootDomain);
var url = (pos === -1)
? this.config.apiEndpoint + '/sites?host=' + location.hostname
: this.config.apiEndpoint + '/sites/' + location.hostname.substr(0, pos);
var promise = this.http.get(url).map(res => res.json()).toPromise();
promise.then(site => this.current = site);
return promise;
}
NOTE: config is just a custom config class. rootDomain would be
'.letterpress.com' for this example and would allow things like
aptaincodeman.letterpress.com.
Any components and other services can now have Site injected into
them and use the .current property which will be a concrete
populated object with no need to wait on any promise within the app.
This approach seemed to cut the startup latency which was otherwise
quite noticeable if you were waiting for the large Angular bundle to
load and then another http request before the bootstrap even began.
original
You can pass it using Angulars dependency injection:
var headers = ... // get the headers from the server
bootstrap(AppComponent, [{provide: 'headers', useValue: headers})]);
class SomeComponentOrService {
constructor(#Inject('headers') private headers) {}
}
or provide prepared BaseRequestOptions directly like
class MyRequestOptions extends BaseRequestOptions {
constructor (private headers) {
super();
}
}
var values = ... // get the headers from the server
var headers = new MyRequestOptions(values);
bootstrap(AppComponent, [{provide: BaseRequestOptions, useValue: headers})]);
In Angular2 final release, the APP_INITIALIZER provider can be used to achieve what you want.
I wrote a Gist with a complete example: https://gist.github.com/fernandohu/122e88c3bcd210bbe41c608c36306db9
The gist example is reading from JSON files but can be easily changed to read from a REST endpoint.
What you need, is basically:
a) Set up APP_INITIALIZER in your existent module file:
import { APP_INITIALIZER } from '#angular/core';
import { BackendRequestClass } from './backend.request';
import { HttpModule } from '#angular/http';
...
#NgModule({
imports: [
...
HttpModule
],
...
providers: [
...
...
BackendRequestClass,
{ provide: APP_INITIALIZER, useFactory: (config: BackendRequestClass) => () => config.load(), deps: [BackendRequestClass], multi: true }
],
...
});
These lines will call the load() method from BackendRequestClass class before your application is started.
Make sure you set "HttpModule" in "imports" section if you want to make http calls to the backend using angular2 built in library.
b) Create a class and name the file "backend.request.ts":
import { Inject, Injectable } from '#angular/core';
import { Http } from '#angular/http';
import { Observable } from 'rxjs/Rx';
#Injectable()
export class BackendRequestClass {
private result: Object = null;
constructor(private http: Http) {
}
public getResult() {
return this.result;
}
public load() {
return new Promise((resolve, reject) => {
this.http.get('http://address/of/your/backend/endpoint').map( res => res.json() ).catch((error: any):any => {
reject(false);
return Observable.throw(error.json().error || 'Server error');
}).subscribe( (callResult) => {
this.result = callResult;
resolve(true);
});
});
}
}
c) To read the contents of the backend call, you just need to inject the BackendRequestClass into any class of you choice and call getResult(). Example:
import { BackendRequestClass } from './backend.request';
export class AnyClass {
constructor(private backendRequest: BackendRequestClass) {
// note that BackendRequestClass is injected into a private property of AnyClass
}
anyMethod() {
this.backendRequest.getResult(); // This should return the data you want
}
}
Let me know if this solves your problem.
Instead of having your entry point calling bootstrap itself, you could create and export a function that does the work:
export function doBootstrap(data: any) {
platformBrowserDynamic([{provide: Params, useValue: new Params(data)}])
.bootstrapModule(AppModule)
.catch(err => console.error(err));
}
You could also place this function on the global object, depending on your setup (webpack/SystemJS). It also is AOT-compatible.
This has the added benefit to delay the bootstrap, whenit makes sense. For instance, when you retrieve this user data as an AJAX call after the user fills out a form. Just call the exported bootstrap function with this data.
The only way to do that is to provide these values when defining your providers:
bootstrap(AppComponent, [
provide(RequestOptions, { useFactory: () => {
return new CustomRequestOptions(/* parameters here */);
});
]);
Then you can use these parameters in your CustomRequestOptions class:
export class AppRequestOptions extends BaseRequestOptions {
constructor(parameters) {
this.parameters = parameters;
}
}
If you get these parameters from an AJAX request, you need to bootstrap asynchronously this way:
var appProviders = [ HTTP_PROVIDERS ]
var app = platform(BROWSER_PROVIDERS)
.application([BROWSER_APP_PROVIDERS, appProviders]);
var http = app.injector.get(Http);
http.get('http://.../some path').flatMap((parameters) => {
return app.bootstrap(appComponentType, [
provide(RequestOptions, { useFactory: () => {
return new CustomRequestOptions(/* parameters here */);
}})
]);
}).toPromise();
See this question:
angular2 bootstrap with data from ajax call(s)
Edit
Since you have your data in the HTML you could use the following.
You can import a function and call it with parameters.
Here is a sample of the main module that bootstraps your application:
import {bootstrap} from '...';
import {provide} from '...';
import {AppComponent} from '...';
export function main(params) {
bootstrap(AppComponent, [
provide(RequestOptions, { useFactory: () => {
return new CustomRequestOptions(params);
});
]);
}
Then you can import it from your HTML main page like this:
<script>
var params = {"token": "#User.Token", "xxx": "#User.Yyy"};
System.import('app/main').then((module) => {
module.main(params);
});
</script>
See this question: Pass Constant Values to Angular from _layout.cshtml.