NodeJS removes or deletes Javascript object - javascript

So, I have been trying to create a litte frontend to backend communication with NextJS and NodeJs.NextJS Api forks a node and this node then listens for requests i make from my api.However, my object crashes or something, idk why.
Here is the code of my node. the process.send(NET_PONG_PACKAGE); starts the communication and tells the api , he is ready for requests, so just you dont wonder. If the API sends the first message, the "message" event is triggered and an error occurs.
import * as Utils from './util'
import {ConnectionHandler} from "./ConnectionHandler";
import {
KafkaMessagePackage,
KafkaResultPackage, NET_KAFKARESPONSE_PACKAGE,
NET_PONG_PACKAGE, NetworkPackage,
NOT_ENOUGH_ARGUMENTS_ERROR, PACKAGECODE_PING_PACKAGE,
SyncPackage, UNKNOWN_PACKAGE_ID, WRONG_NODE_TYPE_ERROR
} from "./Variables";
import {Manager} from "./KafkaManager";
const nprocess = require("node:process")
const prefix = "[NODEJS] "
// Argument Handling
const args:Array<string> = nprocess.argv;
const arg:string = args[2];
if(arg == undefined || arg != '-f'){
Utils.killProcess(nprocess,NOT_ENOUGH_ARGUMENTS_ERROR);
}
class myClass {
public validateMyRequest(json_message:any){
const message:NetworkPackage = json_message != undefined ? json_message : JSON.parse(json_message);
switch (message.reqID) {
case PACKAGECODE_PING_PACKAGE:
this.sendProcessCreatedPackage();
break;
case 0:
this.sendKafkaRequest(message);
this.sendKafkaResponsePackage();
break;
default:
this.logError(prefix + UNKNOWN_PACKAGE_ID)
break;
}
}
private sendKafkaRequest(message:any) {
const kafkaManager:Manager = new Manager(message.hostIP);
kafkaManager.sendMessageToKafka(message.topic,message.message);
}
private sendKafkaResponsePackage() {
if(!process.send){
this.logError(prefix + WRONG_NODE_TYPE_ERROR);
return;
}
this.sendMessage(NET_KAFKARESPONSE_PACKAGE);
}
private sendProcessCreatedPackage(){
this.sendMessage(NET_PONG_PACKAGE)
}
private sendMessage(messagePacke:KafkaResultPackage):void
private sendMessage(messagePackage:SyncPackage):void {
if(process.send){
process.send(messagePackage);
}
}
private logError(errorMessage:string):void{
console.log(errorMessage)
}
}
process.on("message", validateMyRequest)
// #ts-ignore
process.send(NET_PONG_PACKAGE);
This code results in following error:
this.sendKafkaRequest(message);
^
TypeError: this.sendKafkaRequest is not a function
at process.validateMyRequest (/Users/marvin.kaiser/kafka-producer/backend/build/myProducer.js:52:22)
at process.emit (node:events:525:35)
at emit (node:internal/child_process:937:14)
at process.processTicksAndRejections (node:internal/process/task_queues:83:21)
This is the code without using an object. It works just perfectly fine If you have a clue on whats going on, please let me know.
import * as Utils from './util'
import {
KafkaMessagePackage,
KafkaResultPackage, NET_KAFKARESPONSE_PACKAGE,
NET_PONG_PACKAGE, NetworkPackage,
NOT_ENOUGH_ARGUMENTS_ERROR, PACKAGECODE_PING_PACKAGE,
SyncPackage, UNKNOWN_PACKAGE_ID, WRONG_NODE_TYPE_ERROR
} from "./Variables";
import {Manager} from "./KafkaManager";
const nprocess = require("node:process")
const prefix = "[NODEJS] "
// Argument Handling
const args:Array<string> = nprocess.argv;
const arg:string = args[2];
if(arg == undefined || arg != '-f'){
Utils.killProcess(nprocess,NOT_ENOUGH_ARGUMENTS_ERROR);
}
function validateMyRequest(json_message:any){
const message:NetworkPackage = json_message != undefined ? json_message : JSON.parse(json_message);
switch (message.reqID) {
case PACKAGECODE_PING_PACKAGE:
sendProcessCreatedPackage();
break;
case 0:
logError("noch alles fein!");
console.log("Hier soll es anscheinend zu einem Fehler kommen:");
console.log(message);
sendKafkaRequest(message);
sendKafkaResponsePackage();
break;
default:
logError(prefix + UNKNOWN_PACKAGE_ID)
break;
}
}
function sendKafkaRequest(message:any) {
const kafkaManager:Manager = new Manager(message.hostIP);
kafkaManager.sendMessageToKafka(message.topic,message.message);
}
function sendKafkaResponsePackage() {
if(!process.send){
logError(prefix + WRONG_NODE_TYPE_ERROR);
return;
}
sendMessage(NET_KAFKARESPONSE_PACKAGE);
}
function sendProcessCreatedPackage(){
sendMessage(NET_PONG_PACKAGE)
console.log("Hier isst noch alles fein 1!")
}
function sendMessage(messagePackage:any):void {
if(process.send){
console.log("[NODE] Nachricht gesendet:")
console.log(messagePackage);
process.send(messagePackage);
}
}
function logError(errorMessage:string):void{
console.log(errorMessage)
}
process.on("message",validateMyRequest)
// #ts-ignore
process.send(NET_PONG_PACKAGE);

Related

Javascript function evaluation?

const debugMode = true;
// if "isCritical" is true, display the message regardless of
// the value of debugMode
function logger(message, isCritical) {
if (isCritical) console.log(message);
else if (debugMode) console.log(message);
}
In the above function, if I issued the following command, would the UTIL. inspect function evaluate "myObj" and not pass the data? I'd preferably not want UTIL.inspect to invoke if "isCritical" is set to false.
logger(
"myObj =\n" +
UTIL.inspect(myObj, {
showHidden: false,
depth: null
}),
false
);
Is there a way to avoid the evaluation of the first parameter in the function when the second parameter is false?
Seperate your code for logging from the decision wether or not it should be executed.
And use a build pipeline that supports tree-shaking.
Live example on rollupjs.org
// config.js
export const DEBUG = false;
// logging.js
import { DEBUG } from "./config.js";
export const log = console.log; // or whatever
export const debug = DEBUG ? (...args) => logger("debug:", ...args) : () => void 0;
// main.js
import { DEBUG } from "./config.js";
import { log, debug } from "./logging.js";
log("this will always be logged");
if (DEBUG) {
log("This will be eliminated when DEBUG=false")
}
// or more concise:
DEBUG && log(`This can be eliminated ${window.location = "/side-effect"}`);
debug("This approach works for simple things: " + location);
debug(`But it has limits ${window.location = "/side-effect"} :(`);

Issue with 'return' outside of a function

I'm currently trying to develop a system that's using ES6 syntax, although when compiling I'm getting the error
GameSettingsStore.js: 'return' outside of function
The current code I've got is:
File index.js
import GameSettingsStore from '../stores/GameSettingsStore';
File GameSettingsStore.js
// Packages
import _ from 'lodash';
// Modules
import AppDispatcher from '../dispatcher/AppDispatcher';
import { Constants } from '../constants/AppConstants';
import * as Events from '../lib/events';
import Clib from '../game-logic/clib';
const CHANGE_EVENT = 'change';
/*
* Display Settings
*/
let _controlsSize = Clib.localOrDef('controlsSize', 'big');
let _graphMode = Clib.localOrDef('graphMode', 'graphics');
let _controlsPosition = Clib.localOrDef('controlsPosition', 'right');
let _leftWidget = Clib.localOrDef('leftWidget', 'players');
/*
* HotKeys
*/
let _hotkeysActive = false;
/*
* Ignore Clients
*/
const _ignoredClientList = JSON.parse(Clib.localOrDef('ignoredList', '{}'));
/*
* Store
*/
const GameSettingsStore = _.extend({}, Events, {
emitChange() {
this.trigger(CHANGE_EVENT);
},
addChangeListener(callback) {
this.on(CHANGE_EVENT, callback);
},
removeChangeListener(callback) {
this.off(CHANGE_EVENT, callback);
},
_setGraphMode(graphMode) {
_graphMode = graphMode;
localStorage.graphMode = graphMode;
},
_setControlsSize(controlsSize) {
_controlsSize = controlsSize;
localStorage.controlsSize = controlsSize;
},
_toggleHotkeysState() {
_hotkeysActive = !_hotkeysActive;
localStorage.hotKeysActive = _hotkeysActive;
},
_ignoreUser(username) {
_ignoredClientList[username.toLowerCase()] = { username };
localStorage.ignoredList = JSON.stringify(_ignoredClientList);
},
_approveUser(username) {
username = username.toLowerCase();
if (_ignoredClientList[username]) {
delete _ignoredClientList[username];
localStorage.ignoredList = JSON.stringify(_ignoredClientList);
}
},
getState() {
return {
graphMode: _graphMode,
controlsSize: _controlsSize,
controlsPosition: _controlsPosition,
leftWidget: _leftWidget,
hotkeysActive: _hotkeysActive
};
},
getIgnoredClientList() {
return _ignoredClientList;
}
});
AppDispatcher.register((payload) => {
const { action } = payload;
switch (action.actionType) {
case Constants.ActionTypes.SET_CONTROLS_SIZE:
GameSettingsStore._setControlsSize(action.controlsSize);
GameSettingsStore.emitChange();
break;
case Constants.ActionTypes.SET_GRAPH_MODE:
GameSettingsStore._setGraphMode(action.graphMode);
GameSettingsStore.emitChange();
break;
case Constants.ActionTypes.TOGGLE_HOYTKEYS_STATE:
GameSettingsStore._toggleHotkeysState();
GameSettingsStore.emitChange();
break;
case Constants.ActionTypes.IGNORE_USER:
GameSettingsStore._ignoreUser(action.username);
GameSettingsStore.emitChange();
break;
case Constants.ActionTypes.APPROVE_USER:
GameSettingsStore._approveUser(action.username);
GameSettingsStore.emitChange();
break;
default:
GameSettingsStore.emitChange();
break;
}
return true;
});
return GameSettingsStore;
I'm assuming the error is coming from the fact I'm not exporting my function, although I'm unsure how I'd go about doing that because of my AppDispatcher code if that is the issue.
export or export default instead of return

Aurelia model with no view returns error on logout

I am new in the Aurelia community and it was given to me a task to make an entire upgrade of my current platform. (more info at the bottom).
Current problem:
Every time i redirect to the logout.js model a message is prompt
ERROR [app-router] TypeError: "this.view is null"
Questions:
How does a custom component "if-permission" can influence on non-view model?
Conlusions:
- I started to believe that any of the big files bellow are influencing the error at all! After commenting most of the code the error what still showing!
- Removed the noView() logic and added an empty logout.html! Guess what? Works like a charm! The logout will redirect to the login page.
This is my RouteConfig.js
{
route: 'logout',
viewPorts: {
main: {
moduleId: PLATFORM.moduleName('pages/logout/logout')
}
},
nav: false,
sidebar: false,
auth: false,
title: 'Logout',
name: 'logout',
}
This is my logout.js
import { noView } from 'aurelia-framework';
import authService from 'services/authService';
import uiService from 'services/uiService';
#noView()
export class LogoutPage {
activate() {
//THE ERROR PROMPTS EVEN WITH THE ABOVE LINES COMMENTED
uiService.impersonate(null, false);
authService.logout();
}
}
After searching a while i noticed that "this.view" is declared on this 2 files:
if-permission.js
import { inject, customAttribute, templateController, BoundViewFactory, ViewSlot } from 'aurelia-framework';
import userService from 'services/api/userService';
#customAttribute('if-permission')
#inject(BoundViewFactory, ViewSlot)
#templateController
export class IfPermission {
constructor(viewFactory, viewSlot) {
this.viewFactory = viewFactory;
this.viewSlot = viewSlot;
this.showing = false;
this.view = null;
this.bindingContext = null;
this.overrideContext = null;
}
/**
* Binds the if to the binding context and override context
* #param bindingContext The binding context
* #param overrideContext An override context for binding.
*/
bind(bindingContext, overrideContext) {
// Store parent bindingContext, so we can pass it down
this.bindingContext = bindingContext;
this.overrideContext = overrideContext;
this.valueChanged(this.value);
}
valueChanged(newValue) {
if (this.__queuedChanges) {
this.__queuedChanges.push(newValue);
return;
}
let maybePromise = this._runValueChanged(newValue);
if (maybePromise instanceof Promise) {
let queuedChanges = this.__queuedChanges = [];
let runQueuedChanges = () => {
if (!queuedChanges.length) {
this.__queuedChanges = undefined;
return;
}
let nextPromise = this._runValueChanged(queuedChanges.shift()) || Promise.resolve();
nextPromise.then(runQueuedChanges);
};
maybePromise.then(runQueuedChanges);
}
}
_runValueChanged(newValue) {
newValue = userService.hasPermission(newValue);
if (!newValue) {
let viewOrPromise;
if (this.view !== null && this.showing) {
viewOrPromise = this.viewSlot.remove(this.view);
if (viewOrPromise instanceof Promise) {
viewOrPromise.then(() => this.view.unbind());
} else {
this.view.unbind();
}
}
this.showing = false;
return viewOrPromise;
}
if (this.view === null) {
this.view = this.viewFactory.create();
}
if (!this.view.isBound) {
this.view.bind(this.bindingContext, this.overrideContext);
}
if (!this.showing) {
this.showing = true;
return this.viewSlot.add(this.view);
}
}
/**
* Unbinds the if
*/
unbind() {
if (this.view === null) {
return;
}
this.view.unbind();
if (!this.viewFactory.isCaching) {
return;
}
if (this.showing) {
this.showing = false;
this.viewSlot.remove(this.view, true, true);
}
this.view.returnToCache();
this.view = null;
}
}
if-user-role.js
import { inject, customAttribute, templateController, BoundViewFactory, ViewSlot } from 'aurelia-framework';
import userService from 'services/api/userService';
#customAttribute('if-user-role')
#inject(BoundViewFactory, ViewSlot)
#templateController
export class IfUserRole {
constructor(viewFactory, viewSlot) {
this.viewFactory = viewFactory;
this.viewSlot = viewSlot;
this.showing = false;
this.view = null;
this.bindingContext = null;
this.overrideContext = null;
}
/**
* Binds the if to the binding context and override context
* #param bindingContext The binding context
* #param overrideContext An override context for binding.
*/
bind(bindingContext, overrideContext) {
// Store parent bindingContext, so we can pass it down
this.bindingContext = bindingContext;
this.overrideContext = overrideContext;
this.valueChanged(this.value);
}
valueChanged(newValue) {
if (this.__queuedChanges) {
this.__queuedChanges.push(newValue);
return;
}
let maybePromise = this._runValueChanged(newValue);
if (maybePromise instanceof Promise) {
let queuedChanges = this.__queuedChanges = [];
let runQueuedChanges = () => {
if (!queuedChanges.length) {
this.__queuedChanges = undefined;
return;
}
let nextPromise = this._runValueChanged(queuedChanges.shift()) || Promise.resolve();
nextPromise.then(runQueuedChanges);
};
maybePromise.then(runQueuedChanges);
}
}
_runValueChanged(newValue) {
newValue = userService.hasRole(newValue);
if (!newValue) {
let viewOrPromise;
if (this.view !== null && this.showing) {
viewOrPromise = this.viewSlot.remove(this.view);
if (viewOrPromise instanceof Promise) {
viewOrPromise.then(() => this.view.unbind());
} else {
this.view.unbind();
}
}
this.showing = false;
return viewOrPromise;
}
if (this.view === null) {
this.view = this.viewFactory.create();
}
if (!this.view.isBound) {
this.view.bind(this.bindingContext, this.overrideContext);
}
if (!this.showing) {
this.showing = true;
return this.viewSlot.add(this.view);
}
}
/**
* Unbinds the if
*/
unbind() {
if (this.view === null) {
return;
}
this.view.unbind();
if (!this.viewFactory.isCaching) {
return;
}
if (this.showing) {
this.showing = false;
this.viewSlot.remove(this.view, true, true);
}
this.view.returnToCache();
this.view = null;
}
}
With this update i have integrated Aurelia-cli, updated aurelia-webpack and all the dependencies. Which made me switch some code like:
Add PLATFORM.moduleName() to all my platform
Add Require to all modules that were only getting components via < compose >

JS Design Pattern for setting a var set for functions

I am working on a react project but I think this question relates to all JS
I have a Token file that contains the following functions:
export default {
set(token) {
Cookies.set(key, token);
return localStorage.setItem(key, token);
},
clear() {
Cookies.remove(key);
return localStorage.removeItem(key);
},
get() {
try {
const retVal = localStorage.getItem(key) || '';
return retVal;
} catch (e) {
return '';
}
},
Now I want to add a set of what are essentially environment variables for the domain of these 3 functions. In my case its based on window.location.hostname but could really be anything.
In this instance lets say we want key to be dev, uat or prod based on window.location.hostname
getKey = host => {
if(host === 'a')
return 'dev'
elseIf (host === 'b')
return 'uat'
else
return 'prod'
}
I think the above is fairly standard to return the key you want. but what if your key has 6 vars, or 8, or 20. How could you set all the vars so that when you call set(), clear() and get() that they have access to them?
Basically I want to wrap the export in a function that sets some vars?
To illustrate this a bit more
class session extends Repo {
static state = {
current: false,
};
current(bool) {
this.state.current = bool;
return this;
}
query(values) {
<Sequelize Query>
});
}
export session = new Session();
using this I can call current(true).session() and sessions state would be set to true. I want to apply a similar pattern to the Token file but I don't want to change all my calls from Token.set(token) to Token.env(hostname).set(token)
This acomplished what I wanted, I had to call the function from within the others as window is not available on load. It essentially illustrates the pattern I was looking for. Thanks for Jim Jeffries for pointing me towards the answer.
class Token {
constructor(props) {
this.state = {
testKey: null,
};
}
setCred = host => {
if (host === 'uat') {
this.state.testKey = 'uat';
} else if (host === 'prod') {
this.state.testKey = 'prod';
} else {
this.state.testKey = 'dev';
}
};
set(token) {
this.setCred(window.location.hostname);
Cookies.set(testKey, token);
return localStorage.setItem(testKey, token);
}
clear() {
this.setCred(window.location.hostname);
Cookies.remove(testKey);
return localStorage.removeItem(testKey);
}
get() {
this.setCred(window.location.hostname);
try {
const retVal = localStorage.getItem(key) || '';
return retVal;
} catch (e) {
return '';
}
}
}
export default new Token();
If anyone else has another idea please share.

Firebase functions (kotlin2js) error: cannot read property 'iterator' of undefined

I'm writing an Android app that stores data in a Firebase Firestore and manipulates it with Firebase Cloud Functions. I've written the server code using kotlin2js. The Cloud Function throws an undefined error when trying to iterate over the properties of a simple object.
Why am i getting this error?
How do I process the data stored in the object?
1) MainActivity.kt
package com.srsly.wtf
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import com.google.firebase.firestore.FirebaseFirestore
import kotlinx.android.synthetic.main.activity_main.button
class MainActivity : AppCompatActivity() {
override fun onCreate(bundle: Bundle?) {
super.onCreate(bundle)
setContentView(R.layout.activity_main)
button.setOnClickListener { _ -> upload() }
}
fun upload() {
FirebaseFirestore.getInstance().collection("test")
.add(TestClass())
.addOnSuccessListener { ref ->
ref.addSnapshotListener { snapshot, _ ->
button.text = snapshot.toObject(TestClass::class.java).foo
}
}
}
data class TestClass(val foo = "bar")
}
2) index.kt
import kotlin.js.Promise
external fun require(module: String): dynamic
external val exports: dynamic
fun main(args: Array<String>) {
val functions = require("firebase-functions")
val admin = require("firebase-admin")
admin.initializeApp(functions.config().firebase)
exports.receiveObj = functions.firestore.document("/test/{testId}").onWrite { event ->
val obj = event.data.data().unsafeCast<Map<String, String>>()
obj.entries.forEach{
val newObj = js("({})")
newObj[it.key.toUpperCase()] = it.value.toUpperCase()
event.data.ref.set(newObj)
}
}
}
3) index.js
(function (_, Kotlin) {
'use strict';
var Unit = Kotlin.kotlin.Unit;
function main$lambda(event) {
var obj = event.data.data();
var tmp$;
tmp$ = obj.entries.iterator();
while (tmp$.hasNext()) {
var element = tmp$.next();
var newObj = {};
newObj[element.key.toUpperCase()] = element.value.toUpperCase();
event.data.ref.set(newObj);
}
return Unit;
}
function main(args) {
var functions = require('firebase-functions');
var admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.receiveObj = functions.firestore.document('/test/{testId}').onWrite(main$lambda);
}
_.main_kand9s$ = main;
main([]);
Kotlin.defineModule('index', _);
return _;
}(module.exports, require('kotlin')));
4) build.gradle for the functions project
buildscript {
ext.kotlin_version = '1.2.21'
repositories {
mavenCentral()
}
dependencies {
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
version '1.0-SNAPSHOT'
apply plugin: 'java'
apply plugin: 'kotlin2js'
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
dependencies {
compile "org.jetbrains.kotlin:kotlin-stdlib-js:$kotlin_version"
testCompile "org.jetbrains.kotlin:kotlin-test-js:$kotlin_version"
testCompile group: 'junit', name: 'junit', version: '4.12'
}
compileKotlin2Js.kotlinOptions {
moduleKind = "commonjs"
outputFile = "functions/index.js"
}
5) the error message from the firebase functions log
TypeError: Cannot read property 'iterator' of undefined
at main$lambda (/user_code/index.js:7:23)
at Object.<anonymous> (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:59:27)
at next (native)
at /user_code/node_modules/firebase-functions/lib/cloud-functions.js:28:71
at __awaiter (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:24:12)
at cloudFunction (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:53:36)
at /var/tmp/worker/worker.js:695:26
at process._tickDomainCallback (internal/process/next_tick.js:135:7)

Categories

Resources