Skip to content

Commit 8a75b9f

Browse files
committed
a little refactoring
1 parent 0ddc98d commit 8a75b9f

8 files changed

Lines changed: 78 additions & 36 deletions

File tree

.vscode/tasks.json

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
{
77
"label": "openflow-tsc-watch",
88
"type": "typescript",
9-
"tsconfig": "../../../c:/code/OpenFlow/OpenFlow/tsconfig.json",
9+
"tsconfig": "OpenFlow/tsconfig.json",
1010
"option": "watch",
1111
"problemMatcher": [
1212
"$tsc-watch"
@@ -15,7 +15,7 @@
1515
{
1616
"label": "openflownodered-tsc-watch",
1717
"type": "typescript",
18-
"tsconfig": "../../../c:/code/OpenFlow/OpenFlowNodeRED/tsconfig.json",
18+
"tsconfig": "OpenFlowNodeRED/tsconfig.json",
1919
"option": "watch",
2020
"problemMatcher": [
2121
"$tsc-watch"

OpenFlow/src/Config.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import { DatabaseConnection } from "./DatabaseConnection";
66
import { Provider } from "./LoginProvider";
77
import { TokenUser } from "./TokenUser";
88
import { Logger } from "./Logger";
9+
import { Util } from "./Util";
910

1011
export class Config {
1112
public static db: DatabaseConnection = null;
@@ -72,7 +73,7 @@ export class Config {
7273
// if anything throws, we retry
7374
var metadata: any = await retry(async bail => {
7475
var reader: any = await fetch({ url });
75-
if (reader === null || reader === undefined) { bail(new Error("Failed getting result")); return; }
76+
if (Util.IsNullUndefinded(reader)) { bail(new Error("Failed getting result")); return; }
7677
var config: any = toPassportConfig(reader);
7778
// we need this, for Office 365 :-/
7879
if (reader.signingCerts && reader.signingCerts.length > 1) {

OpenFlow/src/Crypt.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import { Base } from "./base";
55
import { TokenUser } from "./TokenUser";
66
import { User } from "./User";
77
import { Config } from "./Config";
8+
import { Util } from "./Util";
89

910
export class Crypt {
1011
static encryption_key: string = Config.aes_secret.substr(0, 32); // must be 256 bytes (32 characters)
@@ -41,10 +42,11 @@ export class Crypt {
4142
}
4243
});
4344
}
44-
4545
static async compare(password: string, passwordhash: string): Promise<boolean> {
4646
return new Promise<boolean>(async (resolve, reject) => {
4747
try {
48+
if (Util.IsNullEmpty(password)) { return reject("Password cannot be empty"); }
49+
if (Util.IsNullEmpty(passwordhash)) { return reject("Passwordhash cannot be empty"); }
4850
bcrypt.compare(password, passwordhash, async (error, res) => {
4951
if (error) { return reject(error); }
5052
resolve(res);
@@ -54,14 +56,12 @@ export class Crypt {
5456
}
5557
});
5658
}
57-
5859
static createToken(item: User | TokenUser, expiresIn: string): string {
5960
var user: TokenUser = new TokenUser(item);
6061
var token: string = jsonwebtoken.sign({ data: user }, Crypt.encryption_key,
6162
{ expiresIn: expiresIn }); // 60 (seconds), "2 days", "10h", "7d"
6263
return token;
6364
}
64-
6565
static verityToken(token: string): TokenUser {
6666
var o: any = jsonwebtoken.verify(token, Crypt.encryption_key);
6767
o.data = TokenUser.assign(o.data);

OpenFlow/src/Util.ts

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
export class Util {
2+
public static IsNullUndefinded(obj: any) {
3+
if (obj === null || obj === undefined) { return true; }
4+
return false;
5+
}
6+
public static IsNullEmpty(obj: any) {
7+
if (obj === null || obj === undefined || obj === "") { return true; }
8+
return false;
9+
}
10+
public static IsString(obj: any) {
11+
if (typeof obj === 'string' || obj instanceof String) { return true; }
12+
return false;
13+
}
14+
public static isObject(obj: any): boolean {
15+
return obj === Object(obj);
16+
}
17+
static isNumeric(num) {
18+
return !isNaN(num)
19+
}
20+
public static FetchFromObject(obj: any, prop: string): any {
21+
if (typeof obj === 'undefined') {
22+
return false;
23+
}
24+
var _index = prop.indexOf('.')
25+
if (_index > -1) {
26+
return Util.FetchFromObject(obj[prop.substring(0, _index)], prop.substr(_index + 1));
27+
}
28+
return obj[prop];
29+
}
30+
public static saveToObject(obj: any, path: string, value: any): any {
31+
const pList = path.split('.');
32+
const key = pList.pop();
33+
const pointer = pList.reduce((accumulator, currentValue) => {
34+
if (accumulator[currentValue] === undefined) accumulator[currentValue] = {};
35+
return accumulator[currentValue];
36+
}, obj);
37+
if (Util.isObject(pointer)) {
38+
pointer[key] = value;
39+
} else {
40+
throw new Error(path + ' is not an object!')
41+
}
42+
return obj;
43+
}
44+
}

OpenFlow/src/WebSocketClient.ts

Lines changed: 15 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ import { UpdateOneMessage } from "./Messages/UpdateOneMessage";
1515
import { DeleteOneMessage } from "./Messages/DeleteOneMessage";
1616
import { Base } from "./base";
1717
import { UpdateManyMessage } from "./Messages/UpdateManyMessage";
18+
import { Util } from "./Util";
1819

1920
interface IHashTable<T> {
2021
[key: string]: T;
@@ -90,7 +91,8 @@ export class WebSocketClient {
9091
}
9192
public async CreateConsumer(queuename: string): Promise<void> {
9293
var autoDelete: boolean = false;
93-
if (queuename === null || queuename === undefined || queuename === "") { queuename = "web." + Math.random().toString(36).substr(2, 9); autoDelete = true; }
94+
95+
if (Util.IsNullEmpty(queuename)) { queuename = "web." + Math.random().toString(36).substr(2, 9); autoDelete = true; }
9496
var consumer = new amqp_consumer(this._logger, Config.amqp_url, queuename);
9597
consumer.OnMessage = this.OnMessage.bind(this);
9698
this.consumers.push(consumer);
@@ -120,7 +122,7 @@ export class WebSocketClient {
120122
}
121123
}
122124
public async sendToQueue(msg: QueueMessage) {
123-
if (msg.queuename === null || msg.queuename === undefined || msg.queuename === "") { throw new Error("sendToQueue, queuename is mandatory") }
125+
if (Util.IsNullEmpty(msg.queuename)) { throw new Error("sendToQueue, queuename is mandatory") }
124126
if (this.consumers.length === 0) { throw new Error("No consumers for client available to send message through") }
125127
var result = this.consumers[0].sendToQueue(msg.queuename, msg.correlationId, { payload: msg.data, jwt: this.jwt });
126128
}
@@ -155,6 +157,8 @@ export class WebSocketClient {
155157
return true;
156158
} catch (error) {
157159
this._logger.error("WebSocketclient::WebSocket error encountered " + error);
160+
this._receiveQueue = [];
161+
this._sendQueue = [];
158162
this.CloseConsumers();
159163
return false;
160164
}
@@ -180,7 +184,7 @@ export class WebSocketClient {
180184
} else {
181185
var buffer: string = "";
182186
msgs.forEach(msg => {
183-
if (msg.data !== null && msg.data !== undefined) { buffer += msg.data; }
187+
if (!Util.IsNullUndefinded(msg.data)) { buffer += msg.data; }
184188
});
185189
this._receiveQueue = this._receiveQueue.filter(function (msg: SocketMessage): boolean { return msg.id !== id; });
186190
var result: Message = Message.frommessage(first, buffer);
@@ -201,35 +205,35 @@ export class WebSocketClient {
201205
this._sendQueue = this._sendQueue.filter(function (msg: SocketMessage): boolean { return msg.id !== id; });
202206
});
203207
if (this._receiveQueue.length > 25 || this._sendQueue.length > 25) {
204-
if (this.user !== null && this.user !== undefined) {
208+
if (!Util.IsNullUndefinded(this.user)) {
205209
this._logger.debug("[" + this.user.username + "] WebSocketclient::ProcessQueue receiveQueue: " + this._receiveQueue.length + " sendQueue: " + this._sendQueue.length);
206210
}
207211
}
208212
}
209213
public async Send<T>(message: Message): Promise<T> {
210214
return new Promise<T>(async (resolve, reject) => {
211215
this._Send(message, ((msg) => {
212-
if (msg.error !== null && msg.error !== undefined) { return reject(msg.error); }
216+
if (!Util.IsNullUndefinded(msg.error)) { return reject(msg.error); }
213217
resolve(msg);
214218
}).bind(this));
215219
});
216220
}
217221
private _Send(message: Message, cb: QueuedMessageCallback): void {
218222
var messages: string[] = this.chunkString(message.data, 500);
219-
if (messages === null || messages === undefined || messages.length === 0) {
223+
if (Util.IsNullUndefinded(messages) || messages.length === 0) {
220224
var singlemessage: SocketMessage = SocketMessage.frommessage(message, "", 1, 0);
221-
if (message.replyto === null || message.replyto === undefined) {
225+
if (Util.IsNullEmpty(message.replyto)) {
222226
this.messageQueue[singlemessage.id] = new QueuedMessage(singlemessage, cb);
223227
}
224228
this._sendQueue.push(singlemessage);
225229
return;
226230
}
227-
if (message.id === null || message.id === undefined) { message.id = Math.random().toString(36).substr(2, 9); }
231+
if (Util.IsNullEmpty(message.id)) { message.id = Math.random().toString(36).substr(2, 9); }
228232
for (let i: number = 0; i < messages.length; i++) {
229233
var _message: SocketMessage = SocketMessage.frommessage(message, messages[i], messages.length, i);
230234
this._sendQueue.push(_message);
231235
}
232-
if (message.replyto === null || message.replyto === undefined) {
236+
if (Util.IsNullEmpty(message.replyto)) {
233237
this.messageQueue[message.id] = new QueuedMessage(message, cb);
234238
}
235239
// setTimeout(() => {
@@ -238,33 +242,24 @@ export class WebSocketClient {
238242
this.ProcessQueue();
239243
}
240244
public chunkString(str: string, length: number): string[] {
241-
if (str === null || str === undefined) { return null; }
245+
if (Util.IsNullEmpty(str)) { return null; }
242246
// tslint:disable-next-line: quotemark
243247
return str.match(new RegExp('.{1,' + length + '}', 'g'));
244248
}
245-
246-
247-
248-
249249
async Queue(data: string, replyTo: string, correlationId: string, queuename: string): Promise<any[]> {
250250
var d: any = JSON.parse(data);
251251
var q: QueueMessage = new QueueMessage();
252252
q.data = d.payload; q.replyto = replyTo;
253253
q.error = d.error;
254254
q.correlationId = correlationId; q.queuename = queuename;
255255
let m: Message = Message.fromcommand("queuemessage");
256-
if (q.correlationId === undefined || q.correlationId === null || q.correlationId === "") { q.correlationId = m.id; }
256+
if (Util.IsNullEmpty(q.correlationId)) { q.correlationId = m.id; }
257257
m.data = JSON.stringify(q);
258258
q = await this.Send<QueueMessage>(m);
259259
if ((q as any).command == "error") throw new Error(q.data);
260260
return q.data;
261261
}
262262

263-
264-
265-
266-
267-
268263
async Query<T extends Base>(collection: string, query: any, projection: any = null, orderby: any = { _created: -1 }, top: number = 500, skip: number = 0): Promise<any[]> {
269264
var q: QueryMessage<T> = new QueryMessage<T>();
270265
q.collectionname = collection; q.query = query;

OpenFlow/src/WebSocketServer.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import { Crypt } from "./Crypt";
77
import { SigninMessage } from "./Messages/SigninMessage";
88
import { SocketMessage } from "./SocketMessage";
99
import { Message } from "./Messages/Message";
10+
import { Util } from "./Util";
1011

1112
export class WebSocketServer {
1213
private static _logger: winston.Logger;
@@ -38,7 +39,7 @@ export class WebSocketServer {
3839
let count: number = WebSocketServer._clients.length;
3940
WebSocketServer._clients = WebSocketServer._clients.filter(function (cli: WebSocketClient): boolean {
4041
try {
41-
if (cli.jwt !== null && cli.jwt !== undefined) {
42+
if (!Util.IsNullEmpty(cli.jwt)) {
4243
var tuser = Crypt.verityToken(cli.jwt);
4344
var payload = Crypt.decryptToken(cli.jwt);
4445
var clockTimestamp = Math.floor(Date.now() / 1000);

OpenFlow/src/amqp_publisher.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import * as winston from "winston";
22
import * as amqplib from "amqplib";
3+
import { Util } from "./Util";
34

45

56
interface IHashTable<T> {
@@ -80,7 +81,7 @@ export class amqp_rpc_publisher {
8081
OnMessage(sender: amqp_rpc_publisher, msg: amqplib.ConsumeMessage): void {
8182
sender._logger.info("OnMessage " + msg.content.toString());
8283
var corr: string = msg.properties.correlationId;
83-
if (this.activecalls[corr] !== null && this.activecalls[corr] !== undefined) {
84+
if (!Util.IsNullUndefinded(this.activecalls[corr])) {
8485
this.activecalls[corr].resolve(msg.content.toString());
8586
this.activecalls[corr] = null;
8687
} else {

OpenFlow/src/public/CommonControllers.ts

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -32,8 +32,8 @@ module openflow {
3232
this.gettoken();
3333
// cleanup();
3434
});
35-
['log', 'warn', 'debug', 'error'].forEach((methodName) => {
36-
//['error2'].forEach((methodName) => {
35+
//['log', 'warn', 'debug', 'error'].forEach((methodName) => {
36+
['error2'].forEach((methodName) => {
3737
const originalMethod = console[methodName];
3838
console[methodName] = (...args) => {
3939
let initiator = 'unknown place';
@@ -319,12 +319,12 @@ module openflow {
319319
}
320320
export class JSONfn {
321321
public static stringify(obj) {
322-
return JSON.stringify(obj, function(key, value) {
322+
return JSON.stringify(obj, function (key, value) {
323323
return (typeof value === 'function') ? value.toString() : value;
324324
});
325325
}
326326
public static parse(str) {
327-
return JSON.parse(str, function(key, value) {
327+
return JSON.parse(str, function (key, value) {
328328
if (typeof value != 'string') return value;
329329
return (value.substring(0, 8) == 'function') ? eval('(' + value + ')') : value;
330330
});
@@ -377,7 +377,7 @@ module openflow {
377377
return new Promise((resolve) => {
378378
try {
379379
if (locale === null || locale === undefined) { return resolve(); }
380-
locale.ready(lib).then(function() {
380+
locale.ready(lib).then(function () {
381381
var value = locale.getString(lib + "." + key);
382382
if (value !== null && value !== undefined && value !== "") {
383383
resolve(value);
@@ -419,15 +419,15 @@ module openflow {
419419
this.locale.ready(lib).then(() => {
420420
var value: string = null;
421421
if (ngModelCtrl !== null) {
422-
ngModelCtrl.$formatters.push(function(value) {
422+
ngModelCtrl.$formatters.push(function (value) {
423423
return calculateValue(value);
424424
});
425425
// value = calculateValue(ngModelCtrl.$viewValue);
426426
// ngModelCtrl.$setViewValue(this.result);
427427
// ngModelCtrl.$render();
428428
} else {
429429
var hashCode = (s: string) => {
430-
return s.split("").reduce(function(a, b) { a = ((a << 5) - a) + b.charCodeAt(0); return a & a }, 0);
430+
return s.split("").reduce(function (a, b) { a = ((a << 5) - a) + b.charCodeAt(0); return a & a }, 0);
431431
}
432432
var watchFunction = () => {
433433
if (attr.value !== null && attr.value !== undefined) {
@@ -536,7 +536,7 @@ module openflow {
536536
async DeleteOne(model: any): Promise<any> {
537537
this.loading = true;
538538
await this.api.Delete(this.collection, model);
539-
this.models = this.models.filter(function(m: any): boolean { return m._id !== model._id; });
539+
this.models = this.models.filter(function (m: any): boolean { return m._id !== model._id; });
540540
this.loading = false;
541541
if (!this.$scope.$$phase) { this.$scope.$apply(); }
542542
}

0 commit comments

Comments
 (0)