Using a string interpolation in a string template undefined object attribute value - javascript

I'm having this weird error:
testObject.ts
import { OobjectA } from './OobjectA';
import { OobjectB } from './OobjectB';
import { OobjectC } from './OobjectC';
export class TestObject{
private _atrrA: number=0;
private _atrr1: string="";
private _atrr2: number = 0;
private _atrr3: number = 0;
private _atrrBt: Date = new Date();
private _atrrC: number =0;
private _atrrD: Date = new Date();
private _atrrError: number = 0;
private _atrr4: number = 0;
private _atrr5: number = 0;
constructor(
oobjectA: OobjectA,
oobjectB: OobjectB,
oobjectC: OobjectC
) {
if (oobjectA !== undefined &&
oobjectB !== undefined &&
oobjectC !== undefined ) {
this._atrrError = oobjectA.atrrError;
this._atrr4 = oobjectB.atrr4;
this._atrr5 = oobjectC.atrr5;
}
}
set atrrA(atrrA){
this._atrrA =atrrA
}
set atrr1(atrr1){
this._atrr1 =atrr1
}
set atrr2(atrr2){
this._atrr2 = atrr2
}
set atrr3(atrr3){
this._atrr3 =atrr3
}
set atrrBt(atrrBt){
this._atrrBt = atrrBt
}
set atrrC(atrrC){
this._atrrC = atrrC
}
set atrrD(atrrD){
this._atrrD = atrrD
}
set atrrError(atrrError){
this._atrrError = atrrError
}
set atrr4(_atrr4){
this._atrr4 = _atrr4
}
set atrr5(atrr5){
this._atrr5 = atrr5
}
get atrrA(){
return this._atrrA
}
get atrr1(){
return this._atrr1
}
get atrr2(){
return this._atrr2
}
get atrr3(){
return this._atrr3
}
get atrrBt(){
return this._atrrBt
}
get atrrC(){
return this._atrrC
}
get atrrD(){
return this._atrrD
}
get atrrError(){
return this._atrrError
}
get atrr4(){
return this._atrr4
}
get atrr5(){
return this._atrr5
}
}
Controller.ts
try{
// ...more code
const oobjectA : OobjectA = new OobjectA ()
oobjectA.atrrError = otherObject[0].atrrError
oobjectB.atrr4 = otherObject2[0].subObject[0].atrr4
const testObject: TestObject = new TestObject(oobjectA, oobjectB, oobjectC)
testObject.atrr1 = "string"
testObject.atrr2 = 1
testObject.atrr3 = 1;
const testObject_id: any = await create_user_function_ejecution_order[5].functionCU(testObject).catch(error => {
create_user_function_ejecution_order[5].status=false
create_user_function_ejecution_order[5].error = error
console.log(error)
})
console.log("testObject",testObject.atrrA?.atrrA)
}catch(e){
// ... more code
}
// ... more code
file.ts
import {db} from "../../connection";
export const insert_data = async(testObject) => {
console.log(testObject)
console.log(testObject._atrrError)
console.log(testObject.atrrError)
console.log(`${testObject.atrrError}`)
console.log(`${testObject._atrrError}`)
const queryString = `
INSERT INTO table (column1, column2, column3, columnError, column4, column5)
VALUES ('${testObject.atrr1}', ${testObject.atrr2}, ${testObject.atrr3}, ${testObject.atrrError} , ${testObject.atrr4}, ${testObject.atr5})
`
console.log(queryString)
const result = await db.query(queryString)
return result[0]
};
output
testObject{
_atrrA: 0,
_atrr1: 'string',
_atrr2: 1,
_atrr3: 1,
_atrrB: 2021-11-24T23:37:42.394Z,
_atrrC: 0,
_atrrD: 2021-11-24T23:37:42.394Z,
_atrrError: 1,
_atrr4: 1,
_atrr5: 1
}
1
1
undefined
undefined
INSERT INTO table (INSERT INTO table (column1, column2, column3, columnError, column4, column5)
VALUES ('string', 1, 1, undefined, 1, 1)
Error: Unknown column 'undefined' in 'field list'
Why it is defined with the value 1 in the cosole.log but in the 3rd console.log it is not defined.
My thought was because some asynchronous thing, but it is in the same file. My second thought was it is taking ownership, but is not a low level language. So my new hypothesis is that the string interpolation have an inside error.
Any other case were it can be other error like this?
devDependencies:
"ts-node": "^10.4.0",
"typescript": "^4.4.4"
nodejs version: v16.13.0

Putting this in an answer just because I need to communicate multiple lines of code which won't be legible in a comment.
When I put this into a file and run that file with nodejs:
const testObject = {
atrr: 1
};
console.log(testObject)
console.log(testObject.atrr)
console.log(`${testObject.atrr}`)
I get this output in the console:
{ atrr: 1 }
1
1
Which is exactly what we would expect. So, apparently there's something different around your object or your environment. The only way I would expect undefined is if the value of the attrr property was something that does not have a .toString() method or if that method returned undefined.
Keep in mind that the template is going to check the type of the value you passed it and, if it isn't a string, it's going to try to convert it to a string. Apparently that string conversion is resulting in undefined.
For any further help, please show exactly how testObject is declared and edit your question to show a minimal, reproducible example.

Related

MongoDB Scheduled Trigger Save Error -- What to Return?

This problem is very annoying. So, I am making a scheduled trigger run every 24 hours. It simply gets items from one collection does some data processing then appends information to another collection. The functioning code works even when the function runs. But it will not let me save because there are "runtime" errors? Even though it was executed perfectly and returned.
Console Error
> result (JavaScript):
EJSON.parse('{"$undefined":true}')
I suppose this has something to do with returning. but when I return null I get this:
> result:
null
> result (JavaScript):
EJSON.parse('null')
when trying to save I get this at the top of the page:
runtime error during function validation
Function Code:
exports = async function() {
const usersCol = context.services.get("SchoologyDashCluster").db("SchoologyDashApp").collection("users");
const gradesCol = context.services.get("SchoologyDashCluster").db("SchoologyDashApp").collection("grades");
var usersCusor = await usersCol.find( ).toArray();
var gradesCusor = await gradesCol.find( ).toArray();
let insert = [];
for (let i = 0; i < usersCusor.length; i++) {
var user = usersCusor[i];
var userSavedGrades = gradesCusor[i].grades
var currentGrades = await getGrades(user.schoologyUID, user.consumerKey, user.secretKey);
var lastGraded = NaN;
let index = gradesCusor[i].grades.length - 1;
while (true) {
if (gradesCusor[i].grades[index].changed == 1) {
lastGraded = index;
break
}
index = index - 1;
}
console.log(lastGraded)
if (userSavedGrades[lastGraded].grades.ga == currentGrades.ga){
currentGrades = { changed : 0, time: new Date().getTime()};
} else {
currentGrades = {changed : 1, grades: currentGrades, time : new Date().getTime()};
}
gradesCol.updateOne(
{"user" : user._id},
{"$push" : {"grades" : currentGrades}}
)
}
// return usersCol.find( );
return null;
};
The answer was simple and now I feel ignorant. Instinctual I put the module imports at the top of the document. However this is incorrect and they need to be placed in the exports function, like so:
exports = function (x,y,z) {
const http = context.http;
return;
}

Correct way to implement a Factory pattern in JavaScript in the following code

The following code is supposed to abstract a temperature sensor for a project involving Arduino.
I have the Sensor function representing the hardware sensor, a sensorFactory function to create instances of the sensor, and a saveSensor / findSensor function that stores / returns the sensor objects from an array.
var sensors = [];
const Sensor = (sensorId, sensorType, sensorName) =>{
var temperature;
let sensor = {
sensorId,
sensorType,
sensorName,
temperature,
readTemperature: (temp) => {
temperature = temp //simulates reading from hardware
},
getTemperature: () => {
console.log(temperature)
}
}
return sensor;
};
const SensorFactory = () =>({
createSensor: (sensorId, sensorType, sensorName) => {
var sensor = {};
switch(sensorType){
case "DS18B20":
sensor = Sensor(sensorId,sensorType, sensorName);
saveSensor(sensor);
return findSensor(sensorId);
break;
}
},
getSensor: (sensorId) =>{
if (sensorId){
return findSensor(sensorId);
}
return sensors;
}
});
const saveSensor = (sensor) => {
sensors.push(sensor);
};
const findSensor = (sensorId) => {
return sensors[sensorId -1];
};
module.exports = SensorFactory;
I have two questions:
Why can't I see the value of the temperature variable when I run the line console.log(JSON.stringify(sensor1))?
const SensorFactory = require ("./sensor.js");
var sensorFactory = SensorFactory();
sensorFactory.createSensor (1,"DS18B20", "Cryogenic Tank");
var sensor1 = sensorFactory.getSensor(1);
sensor1.readTemperature(200);
sensor1.getTemperature(); //prints 200
sensor1.readTemperature(100); //prints 100
sensor1.getTemperature();
sensor1.readTemperature(10); //prints 10
sensor1.getTemperature();
console.log(JSON.stringify(sensor1))
Expected:
{"sensorId":1,"sensorType":"DS18B20","sensorName":"Cryogenic Tank", "temperature": 10}
Actual output:
{"sensorId":1,"sensorType":"DS18B20","sensorName":"Cryogenic Tank"}
I believe that temperature (A) in the following block is a private variable so it should not be accessible from outside the object, but shouldn't I be able to see the temperature variable (B) when I run console.log(JSON.stringify(sensor1))?
const Sensor = (sensorId, sensorType, sensorName) =>{
var temperature; <----A----private.
let sensor = {
sensorId,
sensorType,
sensorName,
temperature, <----B----I should be able to see this, right?
readTemperature: (temp) => {
temperature = temp;
console.log('readTemperature');
},
getTemperature: () => {
console.log('getTemperature');
console.log(temperature); }
}
return sensor;
};
I am very rusty with JS. Can you please help me understand where I am conceptually wrong? How would you modify the code so that it works as expected?
Here's some refactoring into modern Javascript (answers the second question, and, as a side effect, also the first ;)
class Sensor {
constructor(id, type, name) {
this.id = id
this.type = type
this.name = name
this.temperature = null
}
readTemperature(temp) {
this.temperature = temp //simulates reading from hardware
}
}
class SensorSet extends Map {
add(id, type, name) {
this.set(id, new Sensor(id, type, name))
return this.get(id)
}
}
let sensors = new SensorSet()
sensors.add(1, "DS18B20", "Cryogenic Tank")
let s1 = sensors.get(1)
s1.readTemperature(200)
console.log(s1.temperature)
s1.readTemperature(100)
console.log(s1.temperature)
s1.readTemperature(10)
console.log(s1.temperature)
console.log(JSON.stringify(s1))
#Bergi's second comment is the solution to my question. I have also followed his advice and eliminated the sensorFactory function that returns the sensorFactory object. Code is much clear now.

vsCode refresh tree when adding new Item

I use the following code to show tree items,
https://github.com/microsoft/vscode-extension-samples/tree/master/tree-view-sample
The items which is shown in the tree is related to a file, if the file changed the number of the tree items should be changed accordingly(using createFileSystemWatcher which works ok), currently I’ve add the code of the file watcher and when debug it stops there (on the getChildren function when I'm changing the file) and I see that I’ve provided the new updated entries (in the code),however the tree doesn’t refreshed with the new data, any idea what am I missing here ? somehow the new updated data is not reflected in the tree. as I new to this topic maybe I miss something. if the code is OK and there is a bug or this is not supported please let me know.
export class TaskTreeDataProvider implements vscode.TreeDataProvider<TreeItem> {
private _onDidChangeTreeData: vscode.EventEmitter<TreeItem | null> = new vscode.EventEmitter<TreeItem | null>();
readonly onDidChangeTreeData: vscode.Event<TreeItem | null> = this
._onDidChangeTreeData.event;
private eeake: Promise<TreeItem[]> | undefined = undefined;
private autoRefresh: boolean = true;
constructor(private context: vscode.ExtensionContext) {
this.autoRefresh = vscode.workspace
.getConfiguration(“sView")
.get("autorefresh");
let filePath = this.fileName;
let fileWatcher = vscode.workspace.createFileSystemWatcher(filePath);
fileWatcher.onDidChange(() => (this.eeake = this.getChildren()), this.refresh());
}
refresh(): void {
this._onDidChangeTreeData.fire();
}
public async getChildren(task?: TreeItem): Promise<TreeItem[]> {
let tasks = await vscode.tasks
.fetchTasks({ type: “run” })
.then(function (value) {
return value;
});
let entry: TreeItem[] = [];
if (tasks.length !== 0) {
for (var i = 0; i < tasks.length; i++) {
entry[i] = new TreeItem(
tasks[i].definition.type,
tasks[i].name,
{
command: “sView.executeTask",
title: "Execute",
arguments: [tasks[i]]
}
);
}
}
return entry;
}
getTreeItem(task: TreeItem): vscode.TreeItem {
return task;
}
}
class TreeItem extends vscode.TreeItem {
type: string;
constructor(
type: string,
label: string,
collapsibleState: vscode.TreeItemCollapsibleState,
command?: vscode.Command
) {
super(label, collapsibleState);
this.type = type;
this.command = command;
this.iconPath = getIcon();
}
}
If there is something missing please let me know and I add, I'm really stuck with it.
If there is another way to refresh the tree please let me know
Last line in constructor looks suspicious to me.
fileWatcher.onDidChange(() => (this.eeake = this.getChildren()), this.refresh());
I believe you mean:
fileWatcher.onDidChange(() => {
this.eeake = this.getChildren();
this.refresh();
});
Your original code actually immediately invokes this.refresh() in constructor and pass the return value as the 2nd arg to fileWatcher.onDidChange(). this.refresh() wasn't part of the listener passed as 1st arg to onDidChange().

Unable to make function to push an array to the redis list in NodeJS

I am using redis list for storing the value for a key in nodeJS. I have made the following function and exported it to another file to make it a api:
async function set(id, ...seats) {
var seatArr = [];
for(var i = 0; i < seats.length; i++)
{
seatArr = seatArr.concat(seats[i]);
}
try{
result = await client.rpush('seats_'+id, ...seatArr);
} catch(err) {
console.log(err)
}
}
module.exports = {
set : set()
};
But I am getting the following error:
{ ReplyError: ERR wrong number of arguments for 'rpush' command
at parseError (/home/shivank/Music/node-app/ticket-booking/node_modules/redis-parser/lib/parser.js:179:12)
at parseType (/home/shivank/Music/node-app/ticket-booking/node_modules/redis-parser/lib/parser.js:302:14) command: 'RPUSH', args: [ 'seats_undefined' ], code: 'ERR' }
Please help me to resolve this.
Problem
You are not exproting a function, you are trying to export the result of the function (which files because you didn't provide the params that it needs).
module.exports = {
set : set(). // <<<---- You are executing the function
};
but you didn't give it any params so the id param is equal to undefined.
From your stacktrace:
..[ 'seats_undefined' ].. // 'seats_'+id === 'seats_'+`undefined` === 'seats_undefined'
Solution
module.exports = {
set : set
};

correct output of async await promise?

I'm using the firstore, and I get information from the first.
Here, I want to retrieve data from the firstore and print it out, but there is a problem with asynchronous mode.
The output is output after undefined.
I want to know how to print it correctly.
When data is received, the function receives data, and the method of receiving data after searching the firestore.
in react component
index = (date) =>{
let date_total = UserAction.getIndex(date)
return date_total
}
render(){
const {user_list} = this.props;
console.log(this.state)
const date = "2020-02-24"
console.log("data",date)
let index = this.index(date) < this
console.log("index", index)
return(...)
and useraction function
export function getIndex(data){
let time_now = moment(data).utc().format()
const user_history_start = moment(time_now).startOf("d").utc().format();
const user_history_end = moment(time_now).endOf("d").utc().format();
let db = loadFB().firestore();
let query = db.collection('users').where('create_date','>=',user_history_start).where('create_date','<=',user_history_end);
let number ;
return query.get().then( docs=>{
number = docs.size
return number
})
}
i want output
data 2020-02-24
index 11 < (firestore given data)
but output
data 2020-02-24
index promise{<pending>} < (firestore given data)
Give me a good solution.
I guess you can't print a promised value in render, set the state and print it instead?
constructor() {
super();
this.state = {
index: null
}
}
getIndex = (date) => {
// --------- update ----------
UserAction.getIndex(date).then(date_total => this.setState({ index: date_total }))
}
componentDidMount() {
const date = "2020-02-24"
// --------- update ----------
this.getIndex(date)
}
render() {
console.log("index", this.state.index)
// will first print null,
// then print the index when the promise is done (re-rendered due to state change)
}
You may want to read this as a reference.

Categories