NodeJs to Typescript - node.js

I need to use nodejs library in my angular project but got example code in nodejs. I have installed library through npm command and import to my component. But it always show undefined.
npm install phenix-edge-auth --save
const TokenBuilder = require('phenix-edge-auth');
// Create a token to access a channel
const token = new TokenBuilder()
.withApplicationId('my-application-id')
.withSecret('my-secret')
.expiresInSeconds(3600)
.forChannel('us-northeast#my-application-id#my-channel.1345')
.build();
How to use this code with angular app?

Import it as angular way..
import * as TokenBuilder from 'phenix-edge-auth'

Related

"ReferenceError: WebSocket is not defined" when using RxJs WebSocketSubject and Angular Universal

I'm setting up an angular 6.x univeral project in order to leverage its SSR (Server-Side Rendering) capabilities. In my app, I'm using websocket communication using RxJs.
More specifically, I'm, using WebSocketSubject and webSocket in my angular universal 6.x project, which works fine on the browser platform. However, when running the node web server (that contains the SSR stuff (Server-Side Rendering)), an error is thrown:
ReferenceError: WebSocket is not defined
Example code:
// not actually code from the reproduction repo
import { WebSocketSubject, webSocket } from 'rxjs/webSocket';
const socket: WebSocketSubject<any> = webSocket('wss://echo.websocket.org');
socket.subscribe(msg => doSomething(msg));
Please note, that the error doesn't occur on the browser version of the app (i.e. ng serve won't throw the error), but only after compiling the SSR stuff and running the express web server. To reproduce the error, the builds have to be run first:
# install dependencies
npm install
# build angular bundles for browser and server platforms
npm run build:client-and-server-bundles
# build the webserver
npm run webpack:server
# start the webserver
npm run serve:ssr
# the app is now being served at http://localhost:8081/
# open it in the browser and the error will occur: 'ReferenceError: WebSocket is not defined'
I've also set up a reproduction repo.
Environment I'm using:
Runtime: Angular 6
RxJS version: 6.2.0, 6.2.1, 6.2.2 (tested all)
Edit 2018-08-02
I was able to address the problem more accurately. It seems, that this is also a webpack problem. Angular Universal creates a js bundle for running the angular app on the node server, but there is natively no websocket implementation on Node. Therefore, it has to be added manually as a dependency (npm package). I tried adding it to the js server bundle (const WebSocket = require('ws'); manually, which resolves the problem (i.e. ReferenceError disappears). However, when I add it to the TypeScript code that gets transcompiled into the js bundle later on, it won't work.
Further details
The webpack loader ts-loader is used for compiling TypeScript => JavaScript
The websocket depedency was added to the package.json: "ws": "^6.0.0"
Attempting to reference the ws dependency by adding const WebSocket = require('ws'); to the uncompiled TypeScript code won't resolve the issue. It would get compiled into var WebSocket = __webpack_require__(333); in the js output file, the dependency won't be able to be resolved.
Manually changing var WebSocket = __webpack_require__(333); => const WebSocket = require('ws'); in the compiled js file would resolve the issue, but of course it's a hack.
So, the questions are:
Can I "force" webpack to compile the dependency const WebSocket = require('ws'); => const WebSocket = require('ws'); (no changes)?
Or, would it might be a better solution, to register this dependency in the angular universal npm package and create a pull request?
The RxJS webSocket function can receive a WebSocket Constructor as an argument. This can be used to run webSocket in a non-browser/universal environment like this.
const WebSocketConstructor = WebSocket || require('ws')
const socket: WebSocketSubject<any> = webSocket({
url: 'wss://echo.websocket.org',
WebSocketCtor: WebSocketConstructor,
});
// OR...
import { WebSocket, ...otherStuff... } from 'ws';
import { webSocket, ...otherStuff... } from 'rxjs/webSocket';
const socket$ = webSocket({
url: 'wss://someplace.com',
WebSocketCtor: WebSocket,
});
All it takes is this:
// set WebSocket on global object
(global as any).WebSocket = require('ws');
And of course, we need the ws dependency as well in the package.json:
npm i ws -s
In nodeJS apps with ES6 or similar, you must use this:
global.WebSocket = require('ws')
For example:
import { WebSocketSubject, webSocket } from 'rxjs/webSocket';
global.WebSocket = require('ws'); // <-- FIX ALL ERRORS
const subject = webSocket('ws://...');
No more errors.
My first answer!! Cheers
I created a npm package using websockets.
To provide compatibility for server side js and browser js i use this code.
(Note: it is typescript)
if (typeof global !== 'undefined') {
(global as any).WebSocket = require('ws');
}
Like you mentioned, the browser already has a WebSocket in its global object window but node does not.
Since the browser does not have global, this simple check works well.
Compiled code:
if (typeof global !== 'undefined') {
global.WebSocket = require('ws');
}

SwaggerUI + NodeJs (Meteor)

I have a meteor app with a REST API by https://atmospherejs.com/simple/json-routes.
Now I want to document my API with SwaggerUI. I already used SwaggerUI in other projects and know you have to create a yaml or json sepc file, which then is being displayed by SwaggerUI.
So now I have discovered there are some existing swagger-ui packages for npm:
https://www.npmjs.com/package/swagger-ui
https://www.npmjs.com/package/swagger-ui-dist
which I installed by meteor npm install swagger-ui-dist --save-dev
But I have no clue what to do next or how to use them.
I am sure it must be something as simple as:
const swaggerui = require('swagger-ui');
swaggerui.specPath(pathToYaml);
swaggerui.url('/api-docs');
Can anyone help me with the first steps?

How to use Native Node Modules in angular running in electron

Problem description:
This is not a duplicate of this Question. I'm not trying to access the electron module (I use a electron wrapper for angular to do this), I'm trying to use a npm native module in angular while running angular inside electron.
Original description:
I have an angular app which I run with electron (A new app, doesn't do anything yet).
To access Bluetooth I use noble and bleno but while they are working from within electron (to test this I added, noble = require('noble') to index.js in the electron folder) they do not work when I add for example noble to the app.compoents.js in angular.
This is my app.component.ts
import { Component } from '#angular/core';
import {ElectronService} from 'ngx-electron';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title: String = 'Colaboration room';
noble = require('noble')
}
I get this error:
WARNING in ./node_modules/bindings/bindings.js 76:43-53 Critical
dependency: the request of a dependency is an expression
While this is only a warning, the angular initial page is no longer displayed ( its empty).
Question:
How can I access node native modules in Angular (when running in electron)?
Additional Information:
Im using angulars default compiler webpack
The native modules are build against the node version from electron
with electron-rebuild.
I use the ngx-electron module to access the electron api from within angular, thus my guessing that I cant just access noble from within angular without some modification.
Folder structure
Solution attempt: (Since I'm new to node and Angular, I'm happy for code improvements !)
Since I use a wrapper to access electrons apis I had no problem with the electron module.
My real problem was that I didn't know how to access native node modules in angular.
One possible solution is to add the native npm module to webpacks script part (I did not test this yet).
The other solution is to use require in electrons main.js and set it as a
global variable.
const noble = require('noble');
global.sharedObj = noble;
You can then access this global variable using electrons api with the angular electron wrapper.
getBluetoothCentralPulgin(){
var es = new ElectronService();
return es.remote.getGlobal('sharedObj');
}

Using library from npm package #google/maps for Ionic 2 project?

this could be silly question from newcomer, but I wonder about can I use Node.js library with stack that Ionic 2 (Node package system with package.json , Angular 2, Cordova) provides. I found interesting for my project library from Google ( I need geocoding for some form validation).
For this moment I added this package to package.json with
npm install #google/maps --save
npm i
I created provider for client consuming, added
import {} from '#google/maps';
and understood that I need some sort of typings for TS:) Is it really an option to use separate from Ionic and Angular libraries or am I wasting my time?
Update
Thanks to #Ivaro18, I managed how to add typings to my project:
npm install #types/google-maps --save
Now I can make something like this:
import GoogleMapsLoader = require('google-maps');
GoogleMapsLoader.URL = 'https://maps.googleapis.com/maps/api/js';
GoogleMapsLoader.KEY = 'qwertyuiopasdfghjklzxcvbnm';
GoogleMapsLoader.LIBRARIES = ['geocode()', 'places'];
GoogleMapsLoader.CLIENT = 'yourclientkey';
GoogleMapsLoader.CHANNEL = 'myChannel';
GoogleMapsLoader.LANGUAGE = 'fr';
GoogleMapsLoader.REGION = 'GB';
GoogleMapsLoader.VERSION = '3.14';
GoogleMapsLoader.WINDOW_CALLBACK_NAME = '__google_maps_api_provider_initializator__';
#Injectable()
export class GoogleMapsClientProvider {
constructor(public http: Http) {
console.log('Hello GoogleMapsClientProvider Provider');
GoogleMapsLoader.createLoader();
};
}
I found about this here but I'm not sure how to use this stuff,e.g.
GoogleMapsLoader.KEY = 'qwertyuiopasdfghjklzxcvbnm';
GoogleMapsLoader.CLIENT = 'yourclientkey';
What is what? Someone tried this lib before? My mandatory task is to use geocoding for address validation.

Firebase reference is empty after requiring new version

The new documentation provides a straightforward method of initialising firebase, for example, this snipped comes directly from the README.md file:
Install the Firebase npm module:
$ npm init
$ npm install --save firebase
In your code, you can access Firebase using:
var firebase = require('firebase');
var app = firebase.intializeApp({ ... });
// ...
But in my installation this is not working, as in, firebase is empty ({} when console logged).
There's another section in the documentation called Include only the features you need, which provides the following snippet:
var firebase = require('firebase/app');
require('firebase/auth');
require('firebase/database');
var app = firebase.initializeApp({ ... });
// ...
This method works for me, so I'm wondering what could I be doing wrong in the first instance?
I'm using browserify, if that helps, but the docs state: The browser version is designed to be used with
a package bundler (e.g., Browserify,
Webpack).

Resources