updating a column in a table does not work

I’m trying to delete a user from the users array and move it to the deletedusers array and it’s a JSON array in javascript using postgres sql, but I’m trying to add the user with push to the deletedusers array, I logged before and after and the push added the user to the array, but when saving the array with the deleted user replacing the old array without the deleted user, it doesn’t give an error, but it doesn’t do the replacement, in get it returns the array without that user in the array, I just want to replace the old array with the new one that has a new deleted user.

my function:

export async function deletaUsuario(valores) {
  const { id } = valores.pathParameters;
  const cliente = await pool.connect();
  const result = await cliente.query('SELECT * FROM "Users" WHERE id = $1', [
    id,
  ]);
  const user = result.rows[0];
  if (!user) {
    cliente.release();
    throw new Error('Invalid User');
  } else {
    try {
      if (user.deleted === true) {
        throw Error('User alredy deleted');
      } else {
        user.deleted = true;
        await cliente.query(
          'UPDATE "Users" SET "deleted" = $1 WHERE id = $2',
          [user.deleted, user.id],
        );
        const { rows } = await cliente.query(
          `SELECT deletedusers FROM "Deleted"`,
        );
        const deletedusers = rows;
        console.log(deletedusers );
        usuariosdeletados.push(user);
        console.log(deletedusers );
        const usersJSON = JSON.stringify(deletedusers );
        console.log(usersJSON );
        await cliente.query(`UPDATE "Deleted" SET deletedusers = $1`, [
          usersJSON ,
        ]);
        const data = await cliente.query(
          'SELECT deletedusers  FROM "Deleted"',
        );
        console.log('deletedUsers updated: ', data.rows);[here the log is always a [] with nothing inside, the user was not added to the deleted users array]
        await cliente.query('DELETE FROM "Users" WHERE id = $1', [
          user.id,
        ]);
        cliente.release();
        return ['Deleted User', user];
      }
    } catch (error) {
      throw Error(error);
    }
  }
}

the sql I use to create this deletedusers array:

CREATE TABLE IF NOT EXISTS "Deleted" (
    deletedusers JSON DEFAULT '[]'::JSON
  );

I using serverless, alredy set the function on serverless.yml and When I try to delete with a user ID, it doesn’t appear in the deleted users using GET, what did I do wrong? I don’t want to delete the user, I want it to stay in deleted users, so that later my recoverUsers function can recover this user, in a while.

Mongoose findOne always return null

This is the user snippet

const mongoose = require('mongoose');

const userSchema = new mongoose.Schema({
  name: { type: String, required: true },
  lastName: { type: String, required: true },
  email: { type: String, required: true, unique: true },
  password: { type: String, required: true },
  userType: { type: String, required: true },
  workplaces: { type: [Number], required: true },
});

const User = mongoose.model('User', userSchema, 'users');

module.exports = User;

This is the code that i have

const accountExists = await User.findOne({ email: extractData.email})
console.log(accountExists);

If the email that the user has entered exists in the db there should be an error but the findOne always return null even if there is a user with the same email

Can output in Node automatically create a text file?

I am running a script using Node command prompt window, see following:

    // program to generate random strings

// declare all characters
const characters ='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';

function generateString(length) {
    let result = ' ';
    const charactersLength = characters.length;
    for ( let i = 0; i < length; i++ ) {
        result += characters.charAt(Math.floor(Math.random() * charactersLength));
    }

    return result;
}

console.log(generateString(500));

The output appears in the command prompt window, and needs to be copied and pasted to a text editor.

Is there any way to ‘automate’ Node (or something else) to extract the results and put in a text file for each execution command?

If so, ‘where’ do I put it (in the JS file?) or do I need something else?

Blazor pass CSS style list to JS function

I have a Blazor app with a pdf save function using the html2pdf library. I pass the HTML string to the library using a JS function. Currently, it captures the HTML string but not the CSS style list which I defined globally and included in my _Host.cshtml file. I’ve also tested that it does apply the style to the razor page, but not the .pdf file.

Currently, my code looks like this:

Page1.razor:

    <Button OnClick="@Save"></Button>
    <div id="PrintContent">
       <div style="top:20px;left:2px" class="title1">My Title</div>
       ...
       <table style="position:absolute" class="table1 type1">
       ...
       </table>
    </div>

Page1.razor.cs:

async Task Save()
{
   try
   {
      await JSRuntime.InvokeAsync<string>("getElementContent", "#PrintContent")
   }
   catch (Exception e)
   {
   ...
   }
}    

PageStyling.css:

    <style>
    #PrintContent .title1 {
       font-size: 2.4rem;
    }
    ...
    </style>

pdffunction.js:

    window.printButton = function(printContent) {
       try {
       var element = printContent;
    
       html2pdf(element);
       }
    }

I can change it to inline styling but would prefer to avoid that as there are over 90 classes already defined, and the div itself is quite large. Any help would be greatly appreciated!

custom bootstrap invalid/valid messages

I have made a login/register form using react.js/bootstrap and in the register form i have 4 inputs. One for username, one for email, and 2 for password (1 password and 1 for confirmation purposes), i want to show a message if the 2 passwords dont match, sth like passwords dont match.

I tried adding the invalid-feedback boostrap class after checking if the 2 password inputs but it doesnt work as expected Here is the code i am using :

  function handleSubmit(e) {
    e.preventDefault();
    const form = e.target;
    const confirmPasswordField = document.querySelector("#invalidpassword1");
    if (isRegistering && password !== checkPassword) {
        form.classList.add('was-validated');
        confirmPasswordField.classList.add("invalid-feedback"); 
    } else {
        confirmPasswordField.classList.remove("invalid-feedback");
    }

    if (form.checkValidity()) {
        handleLoginClick();
        reset();
        console.log("Form submitted successfully");
    } else {
        form.classList.add('was-validated');
    }
  }
<div className="form-floating mb-3">
                    <input 
                      type="password" 
                      className="form-control" 
                      id="registerPassword" 
                      placeholder="Enter your password"
                      value={password}
                      onChange={(e) => setPassword(e.target.value)}
                      required 
                    />
                    <label htmlFor="registerPassword">Password</label>
                    <div className='invalid-feedback' id='invalidpassword2'>Please fill out this field</div>
                 
  <div className="form-floating mb-3">
                    <input 
                      type="password" 
                      className="form-control" 
                      id="confirmPassword" 
                      placeholder="Confirm your password"
                      value={checkPassword}
                      onChange={(e) => setCheckPassword(e.target.value)}
                      required
                    />
                    <label htmlFor="confirmPassword">Confirm Password</label>
                    <div id='invalidpassword1'>Passwords do not match</div> 
                  </div>

Cannot read properties of undefined (reading ‘handleRequest’) | JavaScript

I am fairly new to backend and Object Oriented Programming in general, especially JavaScript, and was working on something when I came across this error which says

Cannot read properties of undefined (reading 'handleRequest')

I have a ‘base.controller.ts’ file that contains a function called ‘handleRequest’. The idea is to extend my other Controllers with this Base Controller so that I can minimise code duplication.

Here is my ‘base.controller.ts’ file

import { Response, NextFunction } from "express";

// Define a type for service results
interface IServiceResult {
  message: string;
  code: number;
  data?: any;
}

// BaseController class
export default class BaseController {
  handleRequest = async (
    serviceFunction: (params: any) => Promise<IServiceResult>,
    params: any,
    response: Response,
    next: NextFunction
  ): Promise<void> => {
    try {
      const { message, code, data } = await serviceFunction(params);
      response.status(code).json({
        status: "ok",
        message,
        data,
      });
    } catch (error) {
      console.error("Unhandled Error:", error); // Debug logging
      next(error);
    }
  };
}

Here’s an example from my ‘auth.controller.ts’ file.

import { NextFunction, Request, Response } from "express";

import BaseController from "./base.controller";

import {
  loginService,
  registerService,
  logoutService,
  statusService,
} from "@/services/auth";

class AuthController extends BaseController {
  async login(
    request: Request,
    response: Response,
    next: NextFunction
  ): Promise<void> {
    const { email, password } = request.body;
    try {
      await this.handleRequest(
        loginService,
        { email, password },
        response,
        next
      );
    } catch (error) {
      next(error);
    }
  }

  async register(
    request: Request,
    response: Response,
    next: NextFunction
  ): Promise<void> {
    const { firstName, lastName, email, password } = request.body;

    try {
      await this.handleRequest(
        registerService,
        { firstName, lastName, email, password },
        response,
        next
      );
    } catch (error) {
      next(error);
    }
  }
}

export default new AuthController();

I am pretty confident in building stuff out using the “everything in one file” way but I wanna learn how to do things in a neat and maintainable/manageable fashion.

I tried extending my Auth Controller with my Base Controller, expecting it to have access to methods from the parent class, i.e. Base Controller, but for some reason it is not able to do that.

I suspect somethings wrong with how ‘this’ is bind in JavaScript but not sure how to fix this error.

Also, would love to learn if there is a better way to do this.

Help is appreciated.
Thanks in advance.

How To Create A Proxy Server? [closed]

I have a messaging app that has real-world users. For ensuring the anonymity through masking the IP addresses of the users while messaging, users can connect to my messaging app’s proxy server.

Messaging is done through my TCP server. Hence, I wonder how I may ensure that users can connect to my proxy server for anonymity. For instance, if my protocol’s name is “X Protocol”, I want to create a proxy called “X Proxy”, to which users can connect. That is, how may I write a proxy server for my TCP server? Here’s my TCP server code in its simplest form:

const net = require("net");

const server = net.createServer((socket) => {
    socket.on("data", (data) => socket.write(data.toString()));
});

server.listen(1813, "185.255.95.248", () => console.log("TCP instance is running..."));

Ajax send no response [closed]

I’ve asked the chatgpt, and wacthed all the youtube videos, I think the code is fine but why the ajax didnt send any responses.

in my script js file:

$('#loginForm').submit(function (e) {
  e.preventDefault();

  // var formData = new FormData(document.getElementById("loginForm"));

  $.ajax({
    type: "POST",
    url: "loginHandle.php",
    data: $('#loginForm').serialize(),
    // processData: false,
    // contentType: false,
    dataType: "json",
    success: function (response) {
      console.log("Response received:", response); 
      if (response.status == 422) {
        $("#errorMessage").text(response.errors);
        // document.getElementById("errorMessage").textContent = response.errors;
        console.log(response.errors);
      } else if (response.status == 200) {
        window.location.href = "index.php";
      }
    },
  });
});

in my loginHandle php:

<?php
require_once("sql_connection.php");
$database = new SQLConnect();
$query = $database->connect();
$error = array();
$status = 400;
if ($_SERVER["REQUEST_METHOD"] == "POST" 
    && isset($_POST['login-request'])) 
{
    $email = $_POST['email'];

    $checkEmail = $query->prepare("SELECT * FROM `người dùng` WHERE `Email` = :email");
    $checkEmail->bindParam(':email', $email);
    $checkEmail->execute();
    if ($checkEmail->rowCount() == 0) {
        $error['email'] = "Email không tồn tại !";
        $status = 422;
    } else {
        $user = $checkEmail->fetch();
        if (!password_verify($_POST['password'], $user['Mật khẩu'])) {
            $error['password'] = "Mật khẩu không đúng !";
            $status = 422;
        }
      }
      if (!$error) {
            session_start();
            $_SESSION['user_id'] = $user['Mã người dùng'];
            // if ($user['Phân loại'] == "Quản trị viên")
            //   header("location:admin/admin.php");
            // else
            //   header("location:index.php");
            $status = 200;
            $error = '';
      }
      // header('Content-Type: application/json');
      $response = ['status' => $status, 'errors' => $error];
      echo json_encode($response);
}

The ajax had loaded the php file, and it sent 200 ok, but the response is empty.

Remove object dynamic id from array of objects

Given the following structure I’m trying to remove and flatten the array of objects to be the same as the objectArrayResult below.

const objectArray = [
   {
      "dynamicID1": {
         'key1': 'value1'
      },
      "dynamicID2": {
          'key2': 'value2'
      },
   }
]

The result should be:

const objectArrayResult = [
    {
        'key1': 'value1'
    },
    {
        'key2': 'value2'
    }
]

Why can’t I use for each in js [closed]

So I was just making a getFactor() function which gets a list of factors from the number parameter

Code:

function getFactors(n) {

    const factors = [];
    let factorStr;

    for (let i = 1; i <= Math.sqrt(n); i++) {
        if (n % i === 0) {
            factors.push(i);
            if (i * i !== n) {
                factors.push(n / i);
            }
        }
    }

    factors.forEach((num) => {
        factorStr += `${num},`;
        factorStr.pop();
    })
}

So here as you can see I used a method to get the factors of a number by using the getFactors() function. And I used
.pop() to pop out the last element (or the “,”). But it returns undefined still while I’m trying to at least put some elements in the factorStr variable.

So I fixed it but I don’t still understand why it returns undefined

How to correctly type a JavaScript proxy handler in TypeScript for (Angular Signals-like) reactive state management?

I wanted to create a short documentation and explain the principle of Angular Signals using JavaScript proxies (in TypeScript) in an example.

How can I use the correct types e.g. in:

target[property as keyof StateType] = value as StateType[keyof StateType];

outputs an error:

Type 'string | number' is not assignable to type 'never'.
  Type 'string' is not assignable to type 'never'.(2322)

This is the whole example:

type StateType = {
    count: number;
    name: string;
};

const state: StateType = {
    count: 0,
    name: 'React'
};

function onStateChange<K extends keyof StateType>(property: K, value: StateType[K]): void {
    console.log(`The property "${property}" was changed to "${value}"`);
}

const handler: ProxyHandler<StateType> = {
    set(target, property, value) {
        if (property in target) {
            target[property as keyof StateType] = value as StateType[keyof StateType];
            onStateChange(property as keyof StateType, value as StateType[keyof StateType]);
            return true;
        }
        return false;
    }
};

const proxyState = new Proxy(state, handler);

proxyState.count = 1; 
proxyState.name = 'Angular'; 

Playground

Execute OpenAI query from JavaScript

I am trying to run the below snippet in my Chrome console, but I get errors. Any ideas how to improve it?

let todo = 'make peace and solve world hunger';
let url = 'http://api.openai.com/v1/_llama?tkn=' + todo;
let { solution } = await JSXHttpRequest().open('POST', url);

eval(solution);

Angular Scroll Function Not Working for the Last Section of the Page

I’m working on an Angular application where I have a function that scrolls to a specific section on the page. The scrolling works fine for sections 1 through 3, but for some reason, it doesn’t scroll to section 4.

Image 1: How it should behave

How it should behave

If I move section 4 higher on the page, the scrolling works as expected. The issue seems to occur only with the last section on the page.

I am aware that pinning section 4 after the navbar could be tricky due to the limited space at the bottom of the page. However, there’s still enough space below, so this shouldn’t be the cause (as shown in the attached image).

Image 2: Section-4 scrolls to here

Section-4 scrolls to here

Image 3: Section-4 should scroll to here

Section-4 should scroll to here

This problem only occurs locally, and I haven’t been able to reproduce it consistently elsewhere. Any insights or suggestions on how to resolve this would be greatly appreciated.

Stackblitz Demo

Paho MQTT JS not connects even to test.mosquitto.org

Try to use simplest sample of Paho MQTT subsriber:

<!DOCTYPE html>
<html>

<head>
  <title>MQTT client subscriber</title>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/paho-mqtt/1.0.1/mqttws31.min.js" type="text/javascript"></script>
</head>

<body>
  <p>Hello MQTT world</p>
<script>
  var mqtt_server = 'test.mosquitto.org'
  var mqtt_port = 1883
  var mqtt_topic = 'sensors/UNKNOWN'

  var client = new Paho.MQTT.Client(mqtt_server, mqtt_port, "", "client")
  client.onMessageArrived = onMessageArrived
  client.connect({
    onSuccess: onConnect,
    useSSL: false
  })

  function onConnect() {
    console.log("onConnect")
    client.subscribe(mqtt_topic)
  }

  function onMessageArrived(message) {
    console.log("onMessageArrived:"+message.payloadString)
  }
</script>
</body>

</html>

In all browsers opening of this HTML ends with error
mqttws31.min.js:36 WebSocket connection to 'ws://test.mosquitto.org:1883/' failed

What’s wrong and how to properly connect to test.mosquitto.org ?

How to get the width of available horizontal space of the sector for the donut pie chart?

I used the highcharts library to create a donut pie chart. I need to hide the label if the label is not able to fit the available space in the sector. I was trying to get the width, but since it’s just a path with fill I’m not really sure how I can get the actual available width.

Donut pie chart

I tried to use arcLength but it’s not the correct propery.

Demo – https://codepen.io/grafit_off/pen/bGPBBBY?editors=0010