ReferenceError: global is not defined with Stream and Angular 7.1 - getstream-io

I'm trying to use Stream with Angular 7, however I am getting the following error.
ReferenceError: global is not defined
ReferenceError: global is not defined
at Object../node_modules/faye/src/util/browser/event.js (event.js:45)
at webpack_require (bootstrap:83)
at Object../node_modules/faye/src/protocol/client.js (client.js:8)
at webpack_require (bootstrap:83)
at Object../node_modules/faye/src/faye_browser.js (faye_browser.js:9)
at webpack_require (bootstrap:83)
at Object../node_modules/getstream/lib/lib/client.js (client.js:25)
at webpack_require (bootstrap:83)
at Object../node_modules/getstream/lib/getstream.js (getstream.js:6)
at webpack_require (bootstrap:83)
at resolvePromise (zone.js:814)
at resolvePromise (zone.js:771)
at zone.js:873
at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:421)
at Object.onInvokeTask (core.js:16147)
at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:420)
at Zone.push../node_modules/zone.js/dist/zone.js.Zone.runTask (zone.js:188)
at drainMicroTaskQueue (zone.js:595)
I am using the package "getstream" from npm version 4.1.0.
Here is a snippet of code and how I am referencing it.
import { Injectable } from '#angular/core';
import { Constants } from './../constants';
import * as stream from 'getstream';
#Injectable({
providedIn: 'root'
})
export class ActivityService {
userToken: string;
streamClient: stream.Client;
constructor(public azureService: AzureService) {
console.log("Activity Service");
}
async initializeClient() {
try {
await this.getUserToken();
if (this.userToken) {
this.streamClient = await stream.connect(Constants.streamKey, this.userToken, Constants.streamAppId);
}
}
catch (error) {
console.log('Error creating stream client - ', error);
throw error;
}
}
I've tried declaring global but I am not sure what else to try. What's the proper way to import and use Stream in this case?

This looks like an Angular issue. They do offer some workarounds for this.
https://github.com/angular/angular-cli/issues/8160
https://github.com/angular/angular-cli/issues/9827#issuecomment-386154063
(window as any).global = window;

Related

how can I do handling in nestjs when not caught

I am using nestjs.
I have created an AllExceptionFilter.
However, once I run the post request api on the httpService and then an error is returned
nestjs will not accept the RESTful API after that.
What should I do?
■ error log
/Users/username/Documents/workspace/project/nestjs/src/shared/filters/custom-exception.filter.ts:29
path: httpAdapter.getRequestUrl(ctx.getRequest()),
^
TypeError: Cannot read properties of undefined (reading 'getRequestUrl')
at AllExceptionsFilter.catch (/Users/username/Documents/workspace/project/nestjs/src/shared/filters/custom-exception.filter.ts:29:25)
at ExceptionsHandler.invokeCustomFilters (/Users/username/Documents/workspace/project/nestjs/node_modules/#nestjs/core/exceptions/exceptions-handler.js:33:26)
at ExceptionsHandler.next (/Users/username/Documents/workspace/project/nestjs/node_modules/#nestjs/core/exceptions/exceptions-handler.js:13:18)
at /Users/username/Documents/workspace/project/nestjs/node_modules/#nestjs/core/router/router-proxy.js:13:35
at processTicksAndRejections (node:internal/process/task_queues:96:5)
■ no try/catch point code
await firstValueFrom(this.httpService.post(
url,
{
id: 'id'
},
));
■ AllExceptionFilter
import {
ExceptionFilter,
Catch,
ArgumentsHost,
HttpException,
HttpStatus,
} from '#nestjs/common';
import { HttpAdapterHost } from '#nestjs/core';
#Catch()
export class AllExceptionsFilter implements ExceptionFilter {
constructor(private readonly httpAdapterHost: HttpAdapterHost) {}
catch(exception: unknown, host: ArgumentsHost): void {
// In certain situations `httpAdapter` might not be available in the
// constructor method, thus we should resolve it here.
const { httpAdapter } = this.httpAdapterHost;
const ctx = host.switchToHttp();
const httpStatus =
exception instanceof HttpException
? exception.getStatus()
: HttpStatus.INTERNAL_SERVER_ERROR;
const responseBody = {
statusCode: httpStatus,
timestamp: new Date().toISOString(),
path: httpAdapter.getRequestUrl(ctx.getRequest()),
};
httpAdapter.reply(ctx.getResponse(), responseBody, httpStatus);
}
}
Looks like an error is thrown by your endpoint, and the exception filter has an error that is triggered when attempting to handle the first exception.
As specified in the stack trace, the error is coming from: custom-exception.filter.ts:29, which is this line: path: httpAdapter.getRequestUrl(ctx.getRequest())
The problem is that httpAdapter in that line is undefined. For some reason DI isn't injecting it.
If you're using this filter globally, note the following from the docs:
Global-scoped filters are used across the whole application, for every controller and every route handler. In terms of dependency injection, global filters registered from outside of any module (with useGlobalFilters() as in the example above) cannot inject dependencies since this is done outside the context of any module. In order to solve this issue, you can register a global-scoped filter directly from any module using the following construction:
import { Module } from '#nestjs/common';
import { APP_FILTER } from '#nestjs/core';
#Module({
providers: [
{
provide: APP_FILTER,
useClass: HttpExceptionFilter,
},
],
})
export class AppModule {}
If you use the above approach you won't need the useGlobalFilters() method.
If you want to bind this filter at the controller level, the following syntax enables DI:
#UseFilters(AllExceptionsFilter)
#Controller("app")
export class AppController {

Custom TypeORM errors in NestJS Service

I am playing around with NestJS and I would like to take the error thrown from TypeORM and convert it into a shape that I can control.
Right now, I'm just trying to catch the error thrown from TypeORM and log it out to see that my custom filter is working correctly. But unfortunately, my console.log statement in the filter is never logging.
Here is a slimmed down version of my service and filter
user.service.ts
export class UserService {
constructor(
#InjectRepository(Users)
private readonly userRepository: Repository<Users>,
) {}
#UseFilters(new TypeOrmFilter())
async create(createUserDto: CreateUserDto) {
const user = this.userRepository.create(createUserDto);
return this.userRepository.save(user);
}
}
type-orm-filter.ts
#Catch()
export class TypeOrmFilter implements ExceptionFilter {
catch(exception: Error, host: ArgumentsHost) {
console.log('\nI have caught an error\n', exception);
throw exception;
}
}
Here is the log output from the error being thrown by TypeORM
[Nest] 61496 - 04/11/2021, 9:01:42 PM [ExceptionsHandler] invalid input syntax for type uuid: "123e4567" +2482ms
QueryFailedError: invalid input syntax for type uuid: "123e4567"
at new QueryFailedError (my-nest-project/error-project-nestjs/node_modules/typeorm/error/QueryFailedError.js:11:28)
at PostgresQueryRunner.<anonymous> (my-nest-project/error-project-nestjs/node_modules/typeorm/driver/postgres/PostgresQueryRunner.js:247:31)
at step (my-nest-project/error-project-nestjs/node_modules/typeorm/node_modules/tslib/tslib.js:141:27)
at Object.throw (my-nest-project/error-project-nestjs/node_modules/typeorm/node_modules/tslib/tslib.js:122:57)
at rejected (my-nest-project/error-project-nestjs/node_modules/typeorm/node_modules/tslib/tslib.js:113:69)
at processTicksAndRejections (internal/process/task_queues.js:93:5)
You missed the await in UserService#create :p
tip: If you configure ESLint properly, this might never happen again because you already marked that method with await (https://eslint.org/docs/rules/require-await). Or just enforce typing the return (https://github.com/typescript-eslint/typescript-eslint/blob/v3.10.1/packages/eslint-plugin/docs/rules/explicit-module-boundary-types.md)

Selenium Webdriver: extending Navigation causes circular dependency issue

I have a very simple app.ts file that looks like this:
import { Navigation, WebDriver } from "selenium-webdriver";
class MyWebDriver extends WebDriver {
navigate(): Navigation {
return new MyNavigation(this);
}
}
class MyNavigation extends Navigation {
constructor(driver: WebDriver) {
super(driver);
}
}
I have also installed the NPM package selenium-webdriver#4.0.0-alpha5 and I'm using NodeJS version 10.15.3.
Now when I build the project and run the app.js file on the command line, I get the following circular dependency exception:
C:\temp\MyTestNodejsProject>node app.js
C:\temp\MyTestNodejsProject\app.js:9
class MyNavigation extends selenium_webdriver_1.Navigation {
^
TypeError: Class extends value undefined is not a constructor or null
at Object.<anonymous> (C:\temp\MyTestNodejsProject\app.js:9:49)
at Module._compile (internal/modules/cjs/loader.js:701:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:712:10)
at Module.load (internal/modules/cjs/loader.js:600:32)
at tryModuleLoad (internal/modules/cjs/loader.js:539:12)
at Function.Module._load (internal/modules/cjs/loader.js:531:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:754:12)
at startup (internal/bootstrap/node.js:283:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)
The above circular dependency exception is complaining about line 9 of the app.js file below:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const selenium_webdriver_1 = require("selenium-webdriver");
class MyWebDriver extends selenium_webdriver_1.WebDriver {
navigate() {
return new MyNavigation(this);
}
}
class MyNavigation extends selenium_webdriver_1.Navigation {
constructor(driver) {
super(driver);
}
}
//# sourceMappingURL=app.js.map
Can someone please help me figure out how to fix this circular dependency? I've spent days on this and don't see where the circular dependency is happening. Please provide a working code snippet.
============ EDIT =============
I did a sanity check to make sure that Navigation was properly imported (to make sure that wasn't the issue) and modified the code to be:
import { Navigation, WebDriver } from "selenium-webdriver";
class MyWebDriver extends WebDriver {
navigate(): Navigation {
return new Navigation(this);
}
}
Then when I built & ran app.js, the circular dependency exception went away, and app.js ran just fine.

TypeError: Cannot read property 'EventEmitter' of undefined typescript nodejs

I have a typescript application running on node.
I am using 'EventEmitter' class to emit a change in variable value.
This is my piece of code,
import events from 'events';
public async updateStream(streamContext: string, state: boolean): Promise<string> {
const eventEmitter = new events.EventEmitter();
if (state === true) {
return StreamManagement.instance.activeStreams.get(streamContext).streamState = 'Paused';
} else {
const streamState = StreamManagement.instance.activeStreams.get(streamContext).streamState = 'Active';
eventEmitter.emit('resume');
return streamState;
}
}
public async waitForStreamActive(stream: Stream) {
const eventEmitter = new events.EventEmitter();
// tslint:disable-next-line:no-unused-expression
return new Promise(( resolve ) => {
eventEmitter.on('resume', resolve );
});
}
This piece of code builds fine. But when i run the code, as in execute the operation, I am getting the following error,
error: errorHandler - Apply - Hit Unhandled exception {"timestamp":"2019-04-29T12:33:49.209Z"}
error: errorHandler - Apply - Cannot read property 'EventEmitter' of undefined - TypeError: Cannot read property 'EventEmitter' of undefined
at StreamResource.updateStream (C:\Vertigo\core\reference_platform\dist\index.js:10695:51)
at StreamService.patchStream (C:\Vertigo\core\reference_platform\dist\index.js:22524:40)
at process._tickCallback (internal/process/next_tick.js:68:7) {"timestamp":"2019-04-29T12:33:49.215Z"}
What am I doing wrong?
I've set up minimal project to reproduce it and immediately ts compiler warns me about:
TS1192: Module '"events"' has no default export.
But this seems to work:
import * as EventEmitter from 'events'
new EventEmitter();

Cannot find module Error while importing node module in angular typescript file

I am trying to create Electron app which can manage Airplay on MacOS
I am using Angular and TypeScript to wrap APIs from this npm package Airplay npm package :
this is the code I am using in TypeScript :
export class AirplaySharing {
public init() {
const airplayer = window['require']('airplayer');
const list = airplayer();
list.on('update', function(player) {
console.log('Found new AirPlay device:', player.name);
});
}
}
I get this error while calling init()
Error: Cannot find module 'airplayer' at
Module._resolveFilename at Function.Module._resolveFilename at
Function.Module._load at Module.require at require at
t.init at new t at bs at gs at Ys
Would this work
import airplayer = require('airplayer');
export class AirplaySharing {
public init() {
const list = airplayer();
list.on('update', function(player) {
console.log('Found new AirPlay device:', player.name);
});
}
}
Also would it be better to make use of the typescript constructor? Like this:
import airplayer = require('airplayer');
export class AirplaySharing {
constructor(public list: airplayer()) {
list.on('update', function(player) {
console.log('Found new AirPlay device:', player.name);
});
}
}
Hope that helps :)
Did you install the package npm install airplayer --save?

Resources