Destructuring object with inner array without all keys

I have an object like this:

const objBefore: 
{
    "id": "3pa99f64-5717-4562-b3fc-2c963f66afa1",
    "number": "5000",
    "enabled": true,
    "classes": [
        {
            "id": "2fc87f64-5417-4562-b3fc-2c963f66afa4",
            "name": "General"
        },
        {
            "id": "7ffcada8-0215-4fb0-bea9-2266836d3b18",
            "name": "Special"
        },
        {
            "id": "6ee973f7-c77b-4738-b275-9a7299b9b82b",
            "name": "Limited"
        }
    ]
}

Using es6, I want to grab everything in the object except the name key of the inner classes array to pass it to an api.

So:

{
    "id": "3pa99f64-5717-4562-b3fc-2c963f66afa1",
    "number": "5000",
    "enabled": true,
    "classes": [
        {"id": "2fc87f64-5417-4562-b3fc-2c963f66afa4"},
        {"id": "7ffcada8-0215-4fb0-bea9-2266836d3b18"},
        {"id": "6ee973f7-c77b-4738-b275-9a7299b9b82b"}
    ]
}

The closest I got was: let {id, number, enabled, classes: [{id}]} = objBefore;

But it only gets me one id in classes. I’ve tried spreading above using [...{id}] or [{...id}]. Same thing.

I find it challenging to get the right mental model for how to think about this when it’s on multiple levels. In my mind, when I say [...{id}] I’m thinking, “I want the id property as an object in the outer classes array, but give me every id in the array!”

Clearly I’m not thinking about this correctly.

I’ve tried it using map to get that part but I’m still having trouble combining it back to the original to produce the desired result. for example:

let classIds = objBefore.classes.map(({id}) => {
    return {
        id 
    }
})

(Using the map syntax, how can I destructure in the function the other keys that are one level higher?)

To combine them I started trying anything and everything, :

let {id, number, enabled, classIds} = {objBefore, [...classIds]} // returns undefined for all

I’d prefer to do it in one statement. But if that’s not possible, then what’s a clean way to do it using map?.

How do you avoid an SQL injection vulnerability without a query builder or an ORM?

Suppose I have a function that looks like the following (ignore any syntax errors here unless they are relevant to the question, I’m new to SQL):

// This function updates the database using the command passed as a parameter
const execute = async (command) => {
    open({
        filename: "test.db",
        driver: sqlite3.Database,
    }).then((db) => {
        db.exec(command);
    });
};

// Takes the user ID and their input and adds it to the database
const createBlogPost = async (userId, text) => {
    await execute(`INSERT INTO posts (user_id, post) VALUES ("${userId}", "${text}");`)
}

There is nothing stopping the user from injecting their own SQL into the blog post text field. Wouldn’t they be able to execute any command they want as long as the syntax is correct? I’m wondering if there’s anything extra you’re supposed to do in order to prevent this, or if it’s best practice to just use an ORM rather than building your own SQL statements.

Many thanks.

Disconnect MutationObserver wrapped in self invoking function

I have created a JavaScript that uses MutationObserver to watch for changes to a website in the console. The script would retrieve some values from a div, log the accumulated sum and also create some elements on the page (omitted in the code below for simplicity).

I wrap the MutationObserver in a self Invoking function to prevent the variables from colliding with the ones used by the website.

Occasionally the script may fail (the script is not robust enough to deal with some differences in pages) and what I am doing is to log out of the page, paste a different script onto the console to make it work again. Or else the sum would be incorrect and the elements would be created in the wrong place.

I understand that the MutationObserver is on its own scope so observer.disconnect(); would not work. Is there other way to disconnect the MutationObserver in the console without having to refresh/log out of the page?

Here is the simplified version of my code:

(function () {  
    const targetNode = document.querySelector('div.content')
    const observerOptions = { childList: true, attributes: false, subtree: false }
    const callback = function (mutationsList, observer) {
      for (const mutation of mutationsList) {
        if (mutation.removedNodes.length > 0 && (mutation.removedNodes[0].classList.contains('some-view'))) {
            // do something here
        }
        if (mutation.addedNodes.length > 0 && (mutation.addedNodes[0].classList.contains('some-view'))) {
            // do something here
        }
      }
    }
  
    const observer = new MutationObserver(callback)
    observer.observe(targetNode, observerOptions)
  })()

Thank you.

Why Instagram “shortcode_media” is undefined?

I was trying to use a library to download videos from instagram, and it uses graphql, but it only downloads videos every now and then, other times it returns an error. The error:

TypeError: Cannot read properties of undefined (reading 'shortcode_media')

The code:

    async function downloadMetaData(url) {
      try {
        const metaData = await axios({
          method: "get",
          url: url,
        });
        return metaData.data.graphql;
      } catch (error) {
        throw error;
      }
    }
    
    function getMediaType(mediaData) {
      if (mediaData.shortcode_media.is_video === true) {
        return "video";
      }
      return "image";
    }

The link of library (if you need local tests)

Could anyone give me a suggestion on how to solve it or recommend another lib?

How do I make the router not render before all queries in a loop are done? (mongoDB) [duplicate]

I have this router:
// get your courses page

router.get('/yourcourses', async (req, res, next) => {
  let results = []
  if(req.user){
    for(let i =0; i<req.user.coursesFollowing.length; i++){
      let course = Course.findOne({ 'published': true, title: req.user.coursesFollowing[i].courseTitle, authorUsername: req.user.coursesFollowing[i].username }).exec(function (err, result) {
        if(err){return next(err)}
        results.push(result)
        console.log(results)
      })
    }
  }
  console.log(results)
  res.render('content', { whichOne: 1, user: req.user, courses: results});
});

I console log the result from the queries it seems to find the right documents, and when i console log the full array it seems okay,

however looking at the terminal I can see the computer prints the values after rendering the page, which means I need to use an async function to wait for the queries to end, however I am used to do it with one query, not multiple queries inside a loop, so how do I do that?

How do I wait until all the queries inside a loop are done before rendering the page? I tried using settimeout() however it is not predicting how much time it will take.
how would I fix this?

THANKS

Integromat / Make – Parse Website Address and Extract Domain?

I am trying to use an integration tool called Integromat (now know as Make) and they have a Text Parser option where I believe I can do what I want, but I am not sure how.

I am setting up a flow and have a webhook set up that receives a payload from another system. One of the fields in the payload is “website link”. It looks like this:

http://www.example.com and also like http://example.com

I want to remove the http:// and also the http://www. when it occurs and be left with the domain name.

I am not finding good search results for this problem as the company is named “make” so I get unintended results. I also looked through their docs and can’t find anything around string replacement that lines up with what I’m trying to do.

I’ve attached a screenshot if it helps show the text parser.

enter image description here

Reloading my React hook page causes my browser to trigger element

As the title already explains a lot of the problem,

I just developed a simple application in React Hook, my current routes are defined by


   <Router>
      <Routes>
        <Route exact path='/' element={<Home/>}/>
        <Route path='/products/:category' element={<ProductBrowsing/>}/>
        <Route path='/productsDetails/:id' element={<ProductDetails/>}/>
        <Route path='/login' element={<Login/>}/>
        <Route path='/register' element={<Register/>}/>
      </Routes>
    </Router>

testing all these routes in my local machine, it was possible to navigate in all pages either by calling the <Link> component or by putting directly through the URL

when I went to the process of deploying my application and putting it inside a VPS, I realized that a call by <Link> is passable unless the /:category attribute is not the same, which causes the page not to load even if the URL changes (and im passing a lot of parameters that doenst affect the page as a result of this), so the next solution imagined was to always refresh the page to force the component to load with the correct URL, but always when I try to refresh the page in my application I get an immediate response from the tag returning “You need to enable JavaScript to run this app.”

basically I can no longer navigate my application and im hopeful to know why

You can check this behavior here -> http://153.92.221.32/

by trying to navigate through the mega menu links inside the navbar and try to refresh the page, or simply change some subcategory inside the megamenu and notice that the URL changes and the components don’t.

React native wrapper component re-renders on each page navigation

I am developing an android app using react-native and i have a but of a struggle of figuring out why my component re-renders on each page navigation.

In my case i have created a wrapper component called Container.android.js

const Container = props => {
  useEffect(() => {
    // fetching some data from async storage
  },[])

  // Using my hook here
  const {code, error} = usePdaScan({ 
    onEvent: (code) => {
        // setting state via useState
    }, 
    onError: (error) => { 
        Alert.alert('Error', error); 
    }, 
    trigger: 'always'
  });

  return <View>
  {props.children}
  </View>
}

Then i declare routes with Stack.Screen where each stack uses a component wrapped with the Container component.

<Stack.Screen name="Overview" component={Overview} />

And my Overview compnent is this

const Overview = props => {
   return <Container>
        <Text>Overview page</Text>
   </Container>
}

My problem is that inside the Container component, there is a hook called usePdaScan. Each time i navigate to another page and the hook gets called, the Container component re-renders twice… I cant get a lead on this… Halp!

How to have Javascript function save two text inputs into one text (.txt) file?

So I’m writing a webpage where the user inputs values into two textarea fields, and once they click on the submit button, the program is supposed to initiate a download of both text inputs and save them into a text file. So far, I’ve figured out how to have only one of the text inputs be saved to the text file, and I’ve been trying to figure out how to get my Javascript function to have this done for both text inputs. Here is my html and javascript code:

 <body>
      <label for="textbox">Textbox1</label>
      <textarea id="textbox1"></textarea>

      <label for="bio">Textbox2</label>
      <textarea id="textbox2"></textarea>

      <button type="button" id="bt" value="Exporter" onclick="saveIndex()" for="textbox"> EXPORT </button>
function saveIndex(){
  var myBlob = new Blob([document.getElementById('textbox').value],{type: "text/plain"});

  var url = window.URL.createObjectURL(myBlob);
  var anchor = document.createElement("a");
  anchor.href = url;
  anchor.download = "textfile.txt";

  anchor.click();
  window.URL.revokeObjectURL(url);
  document.removeChild(anchor);
}

I know I need to probably create a new Blob for my second textarea tag, but I’ve tried that and also tried different ways to implement it into my function without any success. I cannot make another function for the second textarea tag, this must all be done within the current saveIndex() function. Any help would be greatly appreciated!

Javascript Clicker Game İsn’t working / The click button is not working

Im trying to make a basic clicker game on JS. But theres a problem.

I tried to make a 2x clicker thing which is the game will ask you if you wanna buy 2x clicker when you reached to 100 clicks. 2x clicks will basically give you 2x clicks.

However i think it broked the entire code since click button is not giving any clicks.

Heres the codes:

JS:

let clickCount = 0;
let clickBoost = false;

document.getElementById("clickButton").onclick = function(){
    clickCount +=1;
    document.getElementById("clickCounter").innerHTML = clickCount;

    if (clickCount += 100){
        let boostyorn = prompt("You have more clicks than 100." + "n" + "n" + "Do you wanna buy 2x Clicks?" + "n" + "(Y/N)")
        if (boostyorn == "Y"){
            document.getElementById("clickCounter").innerHTML = clickCount - 100;
            clickBoost = true;
        }
        else{
            alert("You didn't bought 2x Clicks.")
        }
    }

    if (clickBoost == true) {
        document.getElementById("clickButton").onclick = function () {
            clickCount += 2;
            document.getElementById("clickCounter").innerHTML = clickCount;
    }
}

}

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Clicker</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <label id= "clickCounter">0</label><br>
    <center><button id= "clickButton">Click</button></center>
    <label id= "clickBoost"

    <script src="index.js"></script>
</body>
</html>

CSS:

#clickCounter{
    display: block;
    text-align: center;
    font-size: 150px;
}
#clickButton{
    display: block;
    text-align: center;
    font-size: 100px;
}

jquery.min.js:2 jQuery.Deferred exception: Unexpected token < in JSON at position 0 SyntaxError: Unexpected token < in JSON at position 0

window.$(window.document).ready(function ($) {
    "use strict";

    //Notification options
    window.toastr.options = {
      "closeButton": false,
      "debug": false,
      "newestOnTop": false,
      "progressBar": false,
      "positionClass": "toast-top-center",
      "preventDuplicates": true,
      "onclick": null,
      "showDuration": "300",
      "hideDuration": "1000",
      "timeOut": "5000",
      "extendedTimeOut": "1000",
      "showEasing": "swing",
      "hideEasing": "linear",
      "showMethod": "fadeIn",
      "hideMethod": "fadeOut"
    };

    var username, password; 

    // Login button click event
    $("#login-btn").on("click", function (e) {
        e.preventDefault();

        // Remove alert box, if exist
        $(window.document).find(".alert").remove();

        var $tag = $(this);
        var $usernameInput = $("input[name="username"]");
        var $passwordInput = $("input[name="password"]");

        // Disable Button & Input fields
        var $btn = $tag.button("loading");
        $usernameInput.attr("disabled", "disabled");
        $passwordInput.attr("disabled", "disabled");

        if (!window.isDemo || (!username || password)) {
          username = $usernameInput.val();
          password = $passwordInput.val();
        }

        // Ajax request to verify access
        $.ajax({
            url: "index.php?action_type=LOGIN",
            type: "POST",
            dataType: "json",
            data: {username: username, password: password},
            success: function (response) {
              if (response.count_user_store > 1) {
                window.location = "store_select.php?redirect_to=" + (getParameterByName('redirect_to') && getParameterByName('redirect_to') !== "undefined" && getParameterByName('redirect_to') !== "null" ? getParameterByName('redirect_to') : '');
              } else {
                $.ajax({
                  url: window.baseUrl + "/"+window.adminDir+"/dashboard.php?active_store_id=" + response.store_id,
                  method: "GET",
                  dataType: "json"
                }).
                then(function(response) {
                  var alertMsg = response.msg;
                  window.toastr.success(alertMsg, "Success!");
                  window.location = getParameterByName('redirect_to') && getParameterByName('redirect_to') !== "undefined" && getParameterByName('redirect_to') !== "null" ? getParameterByName('redirect_to') : window.baseUrl + "/"+window.adminDir+"/dashboard.php";
                }, function(response) {
                  var errorMsg = JSON.parse(response.responseText);
                  var alertMsg = "<div>";
                      alertMsg += "<p>" + errorMsg.errorMsg + ".</p>";
                      alertMsg += "</div>";
                  window.toastr.warning(alertMsg, "Warning!");
                });
              }
            },
            error: function (response) {
                $btn.button("reset");
                $usernameInput.attr("disabled", false);
                $passwordInput.attr("disabled", false);
                if (isHTML(response.responseText)) {
                  window.location = window.baseUrl+"/"+adminDir+"/dashboard.php";
                } else {
                  window.toastr.warning(JSON.parse(response.responseText).errorMsg, "Warning!");
                }
            }
        });
    });

    $("#credentials table tbody tr").on("click", function (e) {
      e.preventDefault();
      username = $(this).find(".username").data("username"); 
      password = $(this).find(".password").data("password");
      $("input[name="username"]").val(username); 
      $("input[name="password"]").val(password); 
      $("#login-btn").trigger("click");
    });

    $(document).delegate(".activate-store", "click", function(e) {
        e.preventDefault();

        var $tag = $(this);
        var actionUrl = $tag.attr("href");
        
        $.ajax({
            url: actionUrl,
            method: "GET",
            cache: false,
            processData: false,
            contentType: false,
            dataType: "json"
        }).
        then(function(response) {
            $(":input[type="button"]").prop("disabled", false);
            var alertMsg = response.msg;
            window.toastr.success(alertMsg, "Success!");
            window.location = getParameterByName('redirect_to') && getParameterByName('redirect_to') !== "undefined" && getParameterByName('redirect_to') !== "null" ? getParameterByName('redirect_to') : window.baseUrl + "/"+window.adminDir+"/dashboard.php";
        }, function(response) {

          var errorMsg = JSON.parse(response.responseText);
          $(":input[type="button"]").prop("disabled", false);
          var alertMsg = "<div>";
              alertMsg += "<p>" + errorMsg.errorMsg + ".</p>";
              alertMsg += "</div>";
          window.toastr.warning(alertMsg, "Warning!");

        });
    });

    // Send Resent Button
    $("#reset-btn").on("click", function (e) {
        e.preventDefault();

        // Remove alert box, if exist
        $(document).find(".alert").remove();

        // Declare button and input fields
        var $tag = $(this);
        var $emailInput = $("input[name="email"]");

        // Disable Button & Input fields
        var $btn = $tag.button("loading");
        $emailInput.attr("disabled", "disabled");
        $("body").addClass("overlay-loader");

        // Ajax request to verify access
        $.ajax({
            url: "index.php?action_type=SEND_PASSWORD_RESET_CODE",
            type: "POST",
            dataType: "json",
            data: {email: $emailInput.val()},
            success: function (response) {
                $("body").removeClass("overlay-loader");
                $btn.button("reset");
                $("input[name="email"]").attr("disabled", false);
                // show success message
                var successMsg = "<div class="alert alert-success">";
                successMsg += "<p><i class="fa fa-check"></i> " + response.msg + ".</p>";
                successMsg += "</div>";
                $(window.document).find(".modal-body").before(successMsg);
            },
            error: function (response) {
                $("body").removeClass("overlay-loader");
                // enable Button & Input fields
                $btn.button("reset");
                $("input[name="email"]").attr("disabled", false);
                // show error message
                var alertMsg = "<div class="alert alert-danger">";
                alertMsg += "<p><i class="fa fa-warning"></i> " + JSON.parse(response.responseText).errorMsg + ".</p>";
                alertMsg += "</div>";
                $(window.document).find(".modal-body").before(alertMsg);
            }
        });
    });

    // Reset Confirm Button
    $("#reset-confirm-btn").on("click", function (e) {
        e.preventDefault();

        // Remove alert box, if exist
        $(document).find(".alert").remove();

        // Declare button and input fields
        var $tag = $(this);

        var $resetCodeInput = $("input[name="fp_code"]");
        var $passwordInput = $("input[name="password"]");
        var $passwordConfirmInput = $("input[name="password_confirm"]");

        // Disable Button & Input fields
        var $btn = $tag.button("loading");
        $passwordInput.attr("disabled", "disabled");
        $passwordConfirmInput.attr("disabled", "disabled");
        $("body").addClass("overlay-loader");

        // Ajax request to verify access
        $.ajax({
            url: "password_reset.php?action_type=RESET",
            type: "POST",
            dataType: "json",
            data: {fp_code: $resetCodeInput.val(),password: $passwordInput.val(),password_confirm: $passwordConfirmInput.val()},
            success: function (response) {
                $("body").removeClass("overlay-loader");
                $btn.button("reset");
                $passwordInput.attr("disabled", false);
                $passwordConfirmInput.attr("disabled", false);
                window.toastr.success(response.msg, "Success!");
                window.location.href = 'index.php';
            },
            error: function (response) {

                $("body").removeClass("overlay-loader");
                // Enable Button & Input fields
                $btn.button("reset");
                $passwordInput.attr("disabled", false);
                $passwordConfirmInput.attr("disabled", false);
                window.toastr.warning(JSON.parse(response.responseText).errorMsg, "Warning!");
            }
        });
    });

    // Centering Loginbox horizontally
    var BoxCentering = function () {
        var $loginBox = $(".login-box");
        var $windowHeight = $(window).height();
        var $loginBoxHeight = $loginBox.innerHeight();
        var $marginTop = ($windowHeight / 2) - ($loginBoxHeight / 2);
        $loginBox.css("marginTop", $marginTop + "px");
    };

    // Login box keeps at center always
    BoxCentering();

    // Centering Login box during scroll
    $(window).on("resize", function () {
        BoxCentering();
    });
});

-React timer clock project- Why does the timer dont run? [duplicate]

I am a beginner at programming and I am trying to make a clock project.

I am just at the start of it but my code is already not working. At this point of the project what I am trying to do is just to have the timer running when I click on play.

It would be so nice if I could get a bit of help there.

Here is my code :


import React, { useState } from 'react';
import ReactDOM from 'react-dom'


function App(props) {
 
let minutes = 25
let seconds = 0 

function clockmecanics () {

  if (seconds===0) {

   seconds = 60 
   minutes --
   

 }

 seconds -- 

}

function updater () { 

  while (minutes>0){

 setTimeout(clockmecanics(),1000)

}
}


 
   return (
     <div>
     <h1> CLOCK </h1>
     <h1> Breaklength : 5 </h1>
     <button> +  </button>
     <button> -  </button>

     <h1> Sessionlength : 25 </h1>
     <button> +  </button>
     <button> -  </button>
     
     <h1> {minutes}:{seconds} </h1>

     <button onClick={()=> updater ()}>PLAY</button>
     
     

     <h2>  </h2>

     

       </div>
   )
 }


ReactDOM.render(
 <App />,
 document.getElementById('container')
);

DOCUMENTOS GCP NÃO FAZ UPLOAD [closed]

Or Google asked for documents to activate minha conta. I sent, but it was wrong. At the time of forwarding or upload button does not work. I don’t know how to contact you to resolve this issue. Does anyone know?

O Google pediu documentos para ativar minha conta. Enviei, mas um estava com erro. Na hora de reenviar o botão upload não funciona. E não sei como fazer contato para resolver isso. Alguém sabe?

enter image description here