Port some amount of code to typescript

This commit is contained in:
David Majdandžić
2023-03-28 01:45:53 +02:00
parent 630c8a1004
commit a26dbcc231
10 changed files with 1954 additions and 1 deletions

View File

@@ -1,5 +1,5 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="main.js" type="NodeJSConfigurationType" nameIsGenerated="true" path-to-js-file="main.js" working-dir="$PROJECT_DIR$">
<configuration default="false" name="main.js" type="NodeJSConfigurationType" nameIsGenerated="true" path-to-js-file="$PROJECT_DIR$/main.js" working-dir="$PROJECT_DIR$">
<method v="2" />
</configuration>
</component>

30
WebsocketTest.ts Normal file
View File

@@ -0,0 +1,30 @@
// @ts-ignore
const Websocket = require('ws');
const ws = new Websocket('ws://localhost:8191');
ws.on('open', function open() {
ws.send('something');
});
interface Animal {
doNoise(): void;
}
class Dog implements Animal {
doNoise(): void {
console.log("woof");
}
}
class Cat implements Animal {
doNoise(): void {
console.log("meow");
}
}
const dog = new Dog();
dog.doNoise();
const cat = new Cat();
cat.doNoise();
let animals: Animal[] = [dog, cat];
animals.forEach(animal => animal.doNoise());

View File

@@ -10,6 +10,7 @@
"author": "",
"license": "ISC",
"dependencies": {
"@types/node": "^18.15.10",
"body-parser": "^1.20.2",
"express": "^4.18.2",
"nanotimer": "^0.3.15",

118
src/client.ts Normal file
View File

@@ -0,0 +1,118 @@
import {SmppSession} from "./smppSession";
import {Job} from "./job";
import Logger from "./logger";
import ClientStatus from "./clientStatus";
import EventEmitter from "events";
export class Client implements SmppSession {
set username(value: string) {
this._username = value;
}
set password(value: string) {
this._password = value;
}
set url(value: string) {
this._url = value;
}
set status(value: ClientStatus) {
this._status = value;
this.eventEmitter.emit(Client.ClientEvents.STATUS_CHANGED, this._status);
this.eventEmitter.emit(Client.ClientEvents.STATE_CHANGED, this.serialize());
}
public static ClientEvents = {
STATUS_CHANGED: "STATUS_CHANGED",
STATE_CHANGED: "STATE_CHANGED",
}
private readonly eventEmitter: EventEmitter;
private readonly logger: object;
private readonly id: number;
private _username: string;
private _password: string;
private _url: string;
private session?: object;
private _status: ClientStatus = ClientStatus.NOT_CONNECTED;
defaultSingleJob?: Job;
defaultMultipleJob?: Job;
private promises: any = {
connect: null,
close: null,
bind: null
}
constructor(id: number, url: string, username: string, password: string) {
this.id = id;
this._url = url;
this._username = username;
this._password = password;
this.eventEmitter = new EventEmitter();
this.logger = new Logger(`Client-${id}`);
this.setStatus(ClientStatus.NOT_CONNECTED)
this.initialize();
}
setStatus(status: ClientStatus): void {
this._status = status;
this.eventEmitter.emit("status", status);
}
initialize(): void {
return;
}
connect(): Promise<void> {
this.promises.connect = new Promise((resolve, reject) => {
if (this._status !== ClientStatus.NOT_CONNECTED) {
this.logger.log1("Client already connected");
reject("Client already connected");
return;
}
this.logger.log1(`Client connecting to ${this._url}`);
this.setStatus(ClientStatus.CONNECTING);
try {
this.session = smpp.connect({
url: this._url,
auto_enquire_link_period: this.auto_enquire_link_period,
}, this.connected.bind(this));
this.session.on('error', this.error.bind(this));
this.session.on('close', this.closed.bind(this));
} catch (e) {
this.logger.log1("Client connection failed to " + this._url);
this.setStatus(ClientStatus.NOT_CONNECTED);
this.session.close();
reject("Client connection failed to " + this._url);
}
this.connectingPromise.resolve = resolve;
this.connectingPromise.reject = reject;
});
return this.connectingPromise.promise;
}
serialize(): string {
throw new Error("Method not implemented.");
}
close(): Promise<void> {
throw new Error("Method not implemented.");
}
sendMultiple(Job: object): Promise<object> {
throw new Error("Method not implemented.");
}
sendPdu(pdu: object): Promise<object> {
throw new Error("Method not implemented.");
}
sendSingle(Job: object): Promise<object> {
throw new Error("Method not implemented.");
}
}

8
src/clientStatus.ts Normal file
View File

@@ -0,0 +1,8 @@
export default class ClientStatus {
static readonly CONNECTING: string = "CONNECTING";
static readonly CONNECTED: string = "CONNECTED";
static readonly BUSY: string = "BUSY";
static readonly BINDING: string = "BINDING";
static readonly BOUND: string = "BOUND";
static readonly NOT_CONNECTED: string = "NOT CONNECTED";
}

9
src/job.ts Normal file
View File

@@ -0,0 +1,9 @@
export class Job {
pdu: object;
perSecond?: number;
count?: number;
serialize(): string {
return JSON.stringify(this);
}
}

72
src/logger.ts Normal file
View File

@@ -0,0 +1,72 @@
// @ts-ignore
import {WriteStream} from "fs";
const fs = require('fs');
// @ts-ignore
const LOG_LEVEL: number = process.env.LOG_LEVEL || 6;
// @ts-ignore
const LOG_FILE: string = process.env.LOG_FILE || "";
export default class Logger {
private clazz: string;
private readonly logLevel: number;
private readonly logFile: string;
private readonly logFileWriteStream: WriteStream | null = null;
constructor(clazz: string) {
this.clazz = clazz;
this.logLevel = LOG_LEVEL;
this.logFile = LOG_FILE;
if (!!this.logFile) {
this.logFileWriteStream = fs.createWriteStream(this.logFile, {flags: 'a'});
}
}
leftPad(str: string, len: number, char: string): string {
str = String(str);
let i: number = -1;
len = len - str.length;
if (char === undefined) {
char = " ";
}
while (++i < len) {
str = char + str;
}
return str;
}
log(logLevel: number, data: any): void {
if (typeof data === "object") {
data = JSON.stringify(data);
}
let date = new Date();
let year: string = this.leftPad(String(date.getFullYear()), 4, '0');
let month: string = this.leftPad(String(date.getMonth() + 1), 2, '0');
let day: string = this.leftPad(String(date.getDate()), 2, '0');
let hours: string = this.leftPad(String(date.getHours()), 2, '0');
let minutes: string = this.leftPad(String(date.getMinutes()), 2, '0');
let seconds: string = this.leftPad(String(date.getSeconds()), 2, '0');
let milliseconds: string = this.leftPad(String(date.getMilliseconds()), 3, '0');
let datePrefix: string = `[${day}/${month}/${year}-${hours}:${minutes}:${seconds}:${milliseconds}]`
let out: string = datePrefix.padEnd(30, ' ') + `[${this.clazz}]`.padEnd(28, ' ') + `(${logLevel})`.padEnd(8, ' ') + data;
if (logLevel <= this.logLevel) {
console.log(out);
}
if (!!this.logFileWriteStream) {
this.logFileWriteStream.write(out + "\n");
}
}
log1 = this.log.bind(this, 1);
log2 = this.log.bind(this, 2);
log3 = this.log.bind(this, 3);
log4 = this.log.bind(this, 4);
log5 = this.log.bind(this, 5);
log6 = this.log.bind(this, 6);
}

1685
src/main.ts Normal file

File diff suppressed because it is too large Load Diff

16
src/smppSession.ts Normal file
View File

@@ -0,0 +1,16 @@
export interface SmppSession {
username: string,
password: string,
sendPdu(pdu: object): Promise<object>;
sendSingle(Job: object): Promise<object>;
sendMultiple(Job: object): Promise<object>;
close(): Promise<void>;
initialize(): void;
serialize(): string;
}

14
tsconfig.json Normal file
View File

@@ -0,0 +1,14 @@
{
"compilerOptions": {
"target": "es6",
"module": "commonjs",
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"moduleResolution": "node",
"esModuleInterop": true
},
"exclude": [
"./node_modules"
]
}