Move a dynamic number of array elements from one collection’s array to another collection’s array in MongoDB

I’m working on a Discord Bot but this question is about the service-end I’ve created for the bot. The scenario I’m working on is as follows, whenever a user deletes their account all of the images uploaded by said user will be removed from the GUILDS collection and placed in the DELETED_CONTENT collection. Specifically, a user’s image data will be removed from a GUILD’s image_pool array and placed in a respective DELETED_CONTENT image_pool array.

The number of images varies by user and the number of GUILDS that a user is associated also varies. image_pool data is dynamic so overwriting that would be nuanced to maintain state, whereas the rest of a GUILD’s data is static.
What I’m looking to achieve below assuming ‘jeskoston’ deletes account. I’ve added a comment to their username for clarity.

Current GUILDS (collection)

{
    "_id" : ObjectId("61b3db8b965d8d06da643edd"),
    "preferred_locale" : "en-US",
    "nsfw" : false,
    "installed_by_id" : "795864504197578834",
    "installed_by_username" : "philjackson",
    "image_pool" : [ 
        {
            "_id" : ObjectId("61eb74edaa9c4c0f53cbff67"),
            "date_uploaded" : "2022-01-21T19:07:25-08:00",
            "uploaded_by_discord_username" : "jeskoston <-- WILL DELETE ACCOUNT", 
            "uploaded_by_id" : "619dadc90565852231712345",
            "image_title" : "Jordan",
            "image_url" : "/uploads/925819329911062589/1642820844573IMG-4148.JPG",
            "likes" : null,
            "flags" : 0,
            "nsfw" : null
        }, 
        {
            "_id" : ObjectId("61eb74edaa9c4c0f53cbfe88"),
            "date_uploaded" : "2022-01-21T19:07:25-08:00",
            "uploaded_by_discord_username" : "andydiscord",
            "uploaded_by_id" : "619dadc90565852231771649",
            "image_title" : "Pippen",
            "image_url" : "/uploads/825519329911062589/5442820844573IMG-1111.png",
            "likes" : null,
            "flags" : 0,
            "nsfw" : null
        }
    ],
    "install_date" : "2021-12-10T22:58:19.504Z",
    "discord" : {
        "id" : "945819329911062589",
        "owner_id" : "795864504197577734",
        "system_channel_id" : "888819329911062592",
        "name" : "bulls"
    }
},
{
    "_id" : ObjectId("61eb9a0cbcbea4139ea17123"),
    "preferred_locale" : "en-US",
    "nsfw" : false,
    "installed_by_id" : "795864504197578834",
    "installed_by_username" : "georgekarl",
    "image_pool" : [
      {
            "_id" : ObjectId("61eb74edaa9c4c0f53cbfe90"),
            "date_uploaded" : "2022-01-21T19:09:30-08:00",
            "uploaded_by_discord_username" : "jeskoston <-- WILL DELETE ACCOUNT",
            "uploaded_by_id" : "619dadc90565852231712345",
            "image_title" : "Malone",
            "image_url" : "/uploads/995519329911062100/7842820844573IMG-4000.jpg",
            "likes" : null,
            "flags" : 0,
            "nsfw" : null
        }
     ],
    "install_date" : "2022-01-22T05:45:48.011Z",
    "discord" : {
        "id" : "549483811550042074",
        "owner_id" : "792864524197578834",
        "system_channel_id" : "849421811440042077",
        "name" : "jazz"
    }
}

Current DELETED_CONTENT (collection):

{
    "_id" : ObjectId("88b3db8b965d8d06da643p09"),
    "preferred_locale" : "en-US",
    "nsfw" : false,
    "installed_by_id" : "795864504197578834",
    "installed_by_username" : "philjackson",
    "guild_uninstalled": false,
    "image_pool" : [ 
        {
            "_id" : ObjectId("61eb74edaa9c4c0f53cbfk3p"),
            "date_uploaded" : "2022-01-21T19:07:25-08:00",
            "date_deleted" : "2022-01-25T01:07:45-08:00",
            "uploaded_by_discord_username" : "andrewdiscord",
            "uploaded_by_id" : "619dadc90565852231771659",
            "image_title" : "Rodman",
            "image_url" : "/uploads/925819329911062589/1232820844573IMG-4148.JPG",
            "likes" : null,
            "flags" : 0,
            "nsfw" : null,
            "date_deleted" : "2022-01-22T19:09:25-08:00",
        },
    ],
    "install_date" : "2021-12-10T22:58:19.504Z",
    "discord" : {
        "id" : "945819329911062589",
        "owner_id" : "795864504197577734",
        "system_channel_id" : "888819329911062592",
        "name" : "bulls"
    }
},
{
    "_id" : ObjectId("61eb9a0cbcbea4139ea17789"),
    "preferred_locale" : "en-US",
    "nsfw" : false,
    "installed_by_id" : "795864504197578834",
    "installed_by_username" : "georgekarl",
    "guild_uninstalled": false,
    "image_pool":[{
            "_id" : ObjectId("888b74edaa9c4c0f53cbff45"),
            "date_uploaded" : "2022-02-23T12:07:11-08:00",
            "date_deleted" : "2022-02-24T11:02:01-08:00",
            "uploaded_by_discord_username" : "jakediscord",
            "uploaded_by_id" : "619dadc9056585223175461f",
            "image_title" : "Stockton",
            "image_url" : "/uploads/925819329911062589/1232820844573IMG-4148.JPG",
            "likes" : null,
            "flags" : 0,
            "nsfw" : null,
            "date_deleted" : "2022-03-22T04:09:00-08:00",
        }
],
    "install_date" : "2022-01-22T05:45:48.011Z",
    "discord" : {
        "id" : "549483811550042074",
        "owner_id" : "792864524197578834",
        "system_channel_id" : "849421811440042077",
        "name" : "jazz"
    }
}

Desired GUILDS (collection) after user jeskoston deletes their account:

{
    "_id" : ObjectId("61b3db8b965d8d06da643edd"),
    "preferred_locale" : "en-US",
    "nsfw" : false,
    "installed_by_id" : "795864504197578834",
    "installed_by_username" : "philjackson",
    "image_pool" : [  
        {
            "_id" : ObjectId("61eb74edaa9c4c0f53cbfe88"),
            "date_uploaded" : "2022-01-21T19:07:25-08:00",
            "uploaded_by_discord_username" : "andydiscord",
            "uploaded_by_id" : "619dadc90565852231771649",
            "image_title" : "Pippen",
            "image_url" : "/uploads/825519329911062589/5442820844573IMG-1111.png",
            "likes" : null,
            "flags" : 0,
            "nsfw" : null
        }
    ],
    "install_date" : "2021-12-10T22:58:19.504Z",
    "discord" : {
        "id" : "945819329911062589",
        "owner_id" : "795864504197577734",
        "system_channel_id" : "888819329911062592",
        "name" : "bulls"
    }
},
{
    "_id" : ObjectId("61eb9a0cbcbea4139ea17123"),
    "preferred_locale" : "en-US",
    "nsfw" : false,
    "installed_by_id" : "795864504197578834",
    "installed_by_username" : "georgekarl",
    "image_pool" : [],
    "install_date" : "2022-01-22T05:45:48.011Z",
    "discord" : {
        "id" : "549483811550042074",
        "owner_id" : "792864524197578834",
        "system_channel_id" : "849421811440042077",
        "name" : "jazz"
    }
}

Desired DELETED_CONTENT (collection) after user jeskoston deletes their account:

{
    "_id" : ObjectId("88b3db8b965d8d06da643p09"),
    "preferred_locale" : "en-US",
    "nsfw" : false,
    "installed_by_id" : "795864504197578834",
    "installed_by_username" : "philjackson",
    "guild_uninstalled": false,
    "image_pool" : [ 
        {
            "_id" : ObjectId("61eb74edaa9c4c0f53cbff67"),
            "date_uploaded" : "2022-01-21T19:07:25-08:00",
            "date_deleted" : "2022-01-22T19:09:25-08:00",
            "uploaded_by_discord_username" : "andrewdiscord",
            "uploaded_by_id" : "619dadc90565852231771659",
            "image_title" : "Rodman",
            "image_url" : "/uploads/925819329911062589/1232820844573IMG-4148.JPG",
            "likes" : null,
            "flags" : 0,
            "nsfw" : null,

        },
        {
            "_id" : ObjectId("61eb74edaa9c4c0f53cbff67"),
            "date_uploaded" : "2022-01-21T19:07:25-08:00",
            "date_deleted" : "2022-01-26T07:09:51-08:00",
            "uploaded_by_discord_username" : "jeskoston <-- ACCT DELETED", 
            "uploaded_by_id" : "619dadc90565852231712345",
            "image_title" : "Jordan",
            "image_url" : "/uploads/925819329911062589/1642820844573IMG-4148.JPG",
            "likes" : null,
            "flags" : 0,
            "nsfw" : null
        }
    ],
    "install_date" : "2021-12-10T22:58:19.504Z",
    "discord" : {
        "id" : "945819329911062589",
        "owner_id" : "795864504197577734",
        "system_channel_id" : "888819329911062592",
        "name" : "bulls"
    }
},
{
    "_id" : ObjectId("61eb9a0cbcbea4139ea17789"),
    "preferred_locale" : "en-US",
    "nsfw" : false,
    "installed_by_id" : "795864504197578834",
    "installed_by_username" : "georgekarl",
    "guild_uninstalled": false,
    "image_pool":[{
            "_id" : ObjectId("888b74edaa9c4c0f53cbff45"),
            "date_uploaded" : "2022-02-21T15:07:11-08:00",
            "date_deleted" : "2022-03-02T04:09:00-08:00",
            "uploaded_by_discord_username" : "jakediscord",
            "uploaded_by_id" : "619dadc9056585223175461f",
            "image_title" : "Stockton",
            "image_url" : "/uploads/925819329911062589/1232820844573IMG-4148.JPG",
            "likes" : null,
            "flags" : 0,
            "nsfw" : null,
            
        },
        {
            "_id" : ObjectId("61eb74edaa9c4c0f53cbfe90"),
            "date_uploaded" : "2022-01-21T19:09:30-08:00",
            "date_deleted" : "2022-23-22T04:09:00-08:00",
            "uploaded_by_discord_username" : "jeskoston <-- ACCT DELETED", 
            "uploaded_by_id" : "619dadc90565852231712345",
            "image_title" : "Malone",
            "image_url" : "/uploads/995519329911062100/7842820844573IMG-4000.jpg",
            "likes" : null,
            "flags" : 0,
            "nsfw" : null
        }
],
    "install_date" : "2022-01-22T05:45:48.011Z",
    "discord" : {
        "id" : "549483811550042074",
        "owner_id" : "792864524197578834",
        "system_channel_id" : "849421811440042077",
        "name" : "jazz"
    }
}

My strategy thus far has been to #1 pull a user’s images from the GUILDS collection but before doing that #2 copy data to push to the DELETED_CONTENT collection.

I have #1 finished

For #2 I have a query that collects a user’s image data and adds a date_deleted timestamp to each image. I also include other GUILD data in query. I only return guild entries where a user has images posted.

('GUILDS').aggregate([
   {

           $project:
          {    
               discord:1,
               install_date:1,
               installed_by_id:1,
               installed_by_username:1,
               preferred_locale:1,
               nsfw:1,
               guild_deleted:1,
             
               user_images:
               {
                   $filter:
                   {
                       input:"$image_pool",
                       as: "image",                             
                       cond:{ $eq: ["$$image.uploaded_by_id",'619dadc90565852231771659'] }
                   }
               }
           }
       },
           {
       $addFields: {
           guild_deleted:false,
           "user_images":{
               $map:{
                   input: "$user_images",
                    as:"image",
                    in:{
                       _id:"$$image._id",
                       date_deleted: "$$NOW",
                       date_uploaded:"$$image.date_uploaded",
                      uploaded_by_discord_username:"$$image.uploaded_by_discord_username",
                       uploaded_by_id:"$$image.uploaded_by_id",
                       image_title:"$$image.image_title",
                       image_url:"$$image.image_url",
                       likes:"$$image.likes",
                        flags:"$$image.flags",
                        nsfw:"$$image.nsfw"
                       }
               }
           }
       }
   },
       {
           $match:{ 'user_images.0':{ $exists: true }    }
       }  
])

I retrieve user data based on an images ‘uploaded_by_id’ value. I include static guild info in the event I have to upsert the whole document, user_images are a user’s images from a GUILD’s respective image_pool(s).

I want to be able to move this data without looping calls to the database. I’ve tried to use bulkWrite but have had no luck, I cannot find a concrete example that has a use-case for a dynamic number of entries. I’ve attempted to create a dynamic string for bulkWrite with no luck. I’ve also attempted to use $merge but I’m having trouble with the pipeline operators under whenMatched field.

Maybe my entire approach is off? I will spare my other attempts since this has gotten long. I’m not sure if anyone can help, but any attempt would be appreciated.

Next.js SSR with API not building properly

“Not building properly” meaning “not finishing building at all”. I’ve set up a very basic blog project with dynamic SSR which fetches data from the Notion-API to generate static blog pages. Everything works fine when I’m running it in next dev – however when trying to build the project, it runs into an endless loop without any errors shown.

One thought I had was the following:
If I understand the sequence of everything correctly, Next.js already tries building the static sites during next build. The dynamic site generation relies on an API that I have also coded within the same project, which forwards requests to Notion in order to obfuscate secrets. Obviously no local API will be active during the build, which I am guessing is the error I’m running into?

To illustrate – here’s the code for the pages that are to be generated:

import Head from 'next/head';

export default function Post( { postData, postBlocks } ) {
  console.log( { postData, postBlocks } );
  return (
    <>

      <Head>
        <title>Placeholder</title>
        <meta name="description" content="" />
      </Head>

      <h1>Placeholder</h1>

    </>
  )
}

// Get further info on the specific "Post" from Notion via my API
export async function getStaticProps( { params } ) {
  const postDataRequest = fetch( `${ process.env.API_ROOT }/posts/${ params.id }` );
  const postBlocksRequest = fetch( `${ process.env.API_ROOT }/blocks/${ params.id }` );

  const [ postData, postBlocks ] = await Promise.all(
    ( await Promise.all( [ postDataRequest, postBlocksRequest ] ) )
      .map( response => response.json() )
  );

  return {
    props: { postData, postBlocks: postBlocks.results },
    revalidate: 86400,
  };

}

// Fetch  all "Posts" from Notion via my API, get their ID and generate a static route for each 
export async function getStaticPaths() {
  const req = await fetch( `${ process.env.API_ROOT }/posts?limit=999` );
  const data = await req.json();

  const paths = data.results.map( page => {
    return { params: { id: page.id } };
  } )

  return {
    paths,
    fallback: false,
  };
}

I’ve also tried to start the API locally and build the project in another terminal, this didn’t work either. Have I missed something somewhere?

I have also published my project on GitHub for further inspection.

How to get index page to show HTML instead of JSON with NEXT JS?

I’m trying out Next.js with a pluralsight course and running into a weird issue where my index page will randomly stop working, then only ever return JSON without any error logging or indication that something is wrong. It doesn’t always start out doing this, but once it does there’s no recovering outside of wiping out what’s in the existing file. Is there maybe a specific syntax for form elements Next needs?

index.js and index.tsx output:

{
  "props": {
    "pageProps": {}
  },
  "page": "/",
  "query": {},
  "buildId": "development",
  "nextExport": true,
  "autoExport": true,
  "isFallback": false,
  "scriptLoader": []
}

The index page as tsx (also happened on a js version which lead me to use npx create-next-app@latest --ts hoping it would work better and I prefer to use TS anyway)

import { useState } from 'react';
import type { NextPage } from 'next';

const About: NextPage = () => {
    const [inputText, setInputText] = useState<string>("");

    return (
        <div>
            <input onChange={(e) => { setInputText(e.target.value) }} placeholder="Enter Text Here" />
            <p>{inputText}</p>
        </div>
    );
}

export default About;

If there’s anything obvious breaking Next please point it out, I’m not sure what’s going on here and am surprised how easy it is to bork a page with such simple html/jsx. Any tips or suggestions appreciated!

how to download the file when selected an option from the dropdown list. The items in the drop down list are from json file

I have json file

[
{
   "name": "Documents",
   "types": [
       {"name": "Documents1",
        "url": "http://www.google.com" },
        {"name": "Documents2",
         "url": "http://www.facebook.com" },
        ] 
},
{
    "name": "binary",
    "types": [
        {"name": "binary1",
         "link": "href=./mosq.tar.gz"
        },
        {"name": "binary2",
         "link": "href=./mosq1.tar.gz" 
        }
        ] 
 }

]

I have the html code for this

<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<html xmlns="http://www.w3.org/1999/xhtml">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-confirm/3.3.2/jquery-confirm.min.js"></script>
 <body>
 <label for="">Documents</label>
 <select id="ddlDocuments">  </select> <br>
 <label for="">Binary Download</label> 
 <select id="ddlbinary">  </select> <br>

<script type="text/javascript">
   $(document).ready(function () {

    // FETCHING DATA FROM JSON FILE
        $.getJSON("test.json",
                function (data) {
            var details = '';
         
            // ITERATING THROUGH OBJECTS
            document.getElementById("ddlDocuments").insertBefore(new Option('', ''), 
            document.getElementById("ddlDocuments").firstChild);
            $.each(data[0].types, function (key, value) {
                var option = document.createElement("OPTION");
                option.innerHTML = value.name;
                option.value = value.url;              
                ddlDocuments.options.add(option);           
            });
            $('#ddlDocuments').on('click', function () {
                var url = $(this).val(); // get selected value
                if (url) { // require a URL
                    window.open(url,'_blank');
                    // window.location = url; // redirect
                }
                 return false;
            });


            document.getElementById("ddlbinary").insertBefore(new Option('', ''), 
            document.getElementById("ddlbinary").firstChild);
            $.each(data[2].types, function (key, value) {
                var option = document.createElement("OPTION");
                option.innerHTML = value.name;
                option.value = value.link;
                ddlbinary.options.add(option);
            });

            $('#ddlbinary').on('click', function () {
                var retVal = confirm("Do you want to download ?");
                if( retVal == true ) {
                    window.location = document.getElementById('test').href;
                     return true;
                } else {
                    event.preventDefault();
                    return false;
                }
            });
        });
    });
</script>

Download

How its working right now is we get 2 dropdowns on the webpage for Documents and binary. On select of an option of binary we get a confirmation box to download or not. on click of yes it would download because i am using the div tag. But how do we download the respective file coming from the json.

It would be great if someone would help me.

Node/Express: How to avoid status code 302 from a POST request made from a redirect button

I am trying to achieve a button that allows the client to navigate to and and from 2 sets of “to do lists”.

I want the button name to say “Home” when on the works to do list, and “Work” when on the home to do list page. and to navigate to and from these pages using just the one button.

I am using node, express and EJS, and my current attempt at making this work is to create an HTML button witch sends a post request to a “divert” route, and then executing a conditional statement to decide which route to redirect to depending on what the current page title is.

However i can redirect from the home page to the work page but once there i can not redirect back to the home page!.

console shows a 302 status code the moment i click the button to redirect me a second time. (from work to home.

I am a freshman on node and Express!

My codes below,

HTML

`<%- include("header") -%>    
<div class="box" id="heading">
<h1><%=listTitle%></h1>
</div>

<div class="box">
<% for (let i =0; i< newListItems.length; i++) { %>
<div class="item">
<input type="checkbox">
<p><%= newListItems[i] %></p>
</div>
<% }; %>

<form class="item" action="/" method="post">
<input type="text" name="newItem" placeholder="New item?" autocomplete="off">
<button type="submit" name="list" value=<%= listTitle %>>+</button>
</form>

</div>

<form class="" action="/divert" method="post">
<button type="submit" class="btn1" name="todoType" value="identify" style="width: 
100px"><%=btnName%></button>
</form> 

<%- include("footer") -%>`

app.js

`//jshint esversion:6

const express = require("express");
const bodyParser = require("body-parser");

// globals.
let items = [];
let workItems = [];
let btnIdentify = "Work";

const app = express();
app.use(bodyParser.urlencoded({extended: true}));

//Send static css file to browser.
app.use(express.static("public"));

app.set('view engine', 'ejs');


app.get("/", function(req, res) {
const date = new Date();
const options = {
weekday: "long",
day: "numeric",
month: "long"
};

let day = date.toLocaleDateString("en-US", options);
res.render('list', {listTitle: day, newListItems: items, btnName: btnIdentify});
});


app.post("/", function(req, res) {
let item = req.body.newItem;

if (req.body.list === "Work")  { //only uses frist word off the listTitle value.
workItems.push(item);
res.redirect("/work");
} else {
items.push(item);
res.redirect("/");
}
console.log(req.body);
})

app.get("/work", function(req,res) {

res.render("list", {listTitle: "Work list", newListItems: workItems, btnName: btnIdentify });
});

app.post("/divert", function(req,res) {
if (req.body.list !== "Work") {
res.redirect("/work");
btnIdentify = "Work";
} else if (req.body.list === "Work") {
res.redirect("/");
btnIdentify = "Home";
}
})

app.listen(3000, function() {
console.log("Server is running on port 3000")
});`

Insecure Use of setAtributeNS()

Im fixing some security issues that AppScan found on my Angular Application, one of them is the insecure use of “setAttributeNS()” I use this method in my application to inject some namespaces in the correct htmlElemnt

I have reader about the setAttribute() XSS vulnerability and that a workaround for it is directly injecting the code in the attribute name instead of using ‘setAttribute()’, but for setAttributeNS() I haven’t found any workaround to avoid this vulnerability

Example code:

.setAttributeNS("http://www.w3.org/1999/xlink", "href", canvas.toDataURL('image/png')

Any suggestions will be appreciated

Smooth scroll – additional margin

I am trying to create template for CMS joomla 4, and I am using Template Toaster tool for such purpose. I have some issue with page converted to onepage style of website. I have set anchors for my menu, and when I click to any position of menu, then page is scrooling to my anchor but my floating menu cover some part of my text. I am trying to find how I can add some margin for smooth scrool and when I select any menu postion then when page will be scrolled to menu then text will be not hidden under menu.

Thank you for support

I’m having problems playing áudio files in Discord

So, It’s been two long days traying to figure what the reck is going on… I’m creating a Bot to my Discord Channel that plays an audio.mp3 when a command is written, like !laugh then the bot should enter the voice channel and reproduce laugh.mp3. I’ve tried in so manny different ways but the bot keeps entering the channel, the green circle quickly appears but no sound is played…

const { join } = require('path');
const { joinVoiceChannel,  createAudioPlayer,  createAudioResource, getVoiceConnection, entersState, StreamType,  AudioPlayerStatus,  VoiceConnectionStatus, AudioResource } = require("@discordjs/voice");

module.exports = {
   name: 'laugh', 
   aliases: ["l"], 

   run: async(client, message, args) => {

   const player = createAudioPlayer()
   const connection = joinVoiceChannel({
   channelId: message.member.voice.channel.id,
   guildId: message.guild.id,
   adapterCreator: message.guild.voiceAdapterCreator
                     }).subscribe(player)
   let resource = createAudioResource(join('./som/', 'laugh.mp3'));
   player.play(resource)
   player.on(AudioPlayerStatus.AutoPaused, () => {
   player.stop();
         
     });
   }
}

I’ve already tried to caugh error but apparently nothing is wrong, I already have all intents in my index.js.

So, anyone could help me find a solution?

How to remove duplicates from different arrays in one array ReactJS

Here is my array. How can I remove duplicates in this type of structure. When I map over arr I get the values of each arrays nested in each object. And I want to filter the duplicated values. This returns : bye hello hello

[

    {
        arr: ['']
        val: "string"
    }
    {
        arr: ['bye', 'hello']
        val: "string"
    }
    {
        arr: ['hello']
        val: "string"
    }

]
    
    
myArray.map(item => item.arr.map((el, index) =>
    <p key={index}>{el}</p>       
))

Create Javascript localStorage for website background change

Hello and big thanks for a all S.O community

I come today because i try to create local storage with Javascript for my users can change background and page settings on my website and find it back when page reload.
I tried many attempt but i’m so beginner for do make it work

    var m = new s.a.Store({
    modules: {
        programs: p,
        preferences: {
            state: {
                background: "images/backgrounds/background2.jpg",
                preferredColor: "#1e90ff",
                isWiFiConnected: !1
            },
            getters: {
                background: function(t) {
                    return t.background
                },
                preferredColor: function(t) {
                    return t.preferredColor
                },
                isWiFiConnected: function(t) {
                    return t.isWiFiConnected
                }
            },
            actions: {},
            mutations: {
                changePreferredColor: function(t, e) {
                    t.preferredColor = e
                },
                changeBackground: function(t, e) {
                    t.background = e
                },
                toggleWiFiConnection: function(t) {
                    t.isWiFiConnected = !t.isWiFiConnected
                }
            }
        },
        filesystem: d
    },
    strict: !1
});
i.a.prototype.$t = function(t) {
    return t
}, i.a.config.devtools = !0, new i.a({
    el: "#app",
    store: m,
    components: {
        App: a.a
    }
})
},
function(t, e, n) {
    "use strict";
    (function(e, n) {
            var r = Object.freeze({});

            function i(t) {
                return null == t
            }

            function o(t) {
                return null != t
            }

            function a(t) {
                return !0 === t
            }

            function s(t) {
                return "string" == typeof t || "number" == typeof t || "symbol" == typeof t || "boolean" == typeof t
            }

            function u(t) {
                return null !== t && "object" == typeof t
            }

 there is the code i tried to add just before without sucess (blank page) :

        var m = { ...localStorage };
    localStorage.getItem("background");
    localStorage.setItem("background"); 

Thanks for your support

Best regards

Javascript return statement doesn’t stop rest of function from completing

I am using Docuware’s API to staple (merge) documents together. I have written my question as simple as I can so people with no Docuware knowledge should be able to understand.

So in my main function, I call another function and check the return value of the called function. If the value equals zero, it should return null – meaning the rest of the function should not run.

const lastStored = await searchDocument("Invoice", ORDER_NUMBER = '', cookie)
console.log("Full id func: " + id)
console.log("id[0]: " + id[0])

if (lastStored[0] === 0) {
    console.log("id[0]: " + id[0])
    return null;
};

I am getting weird errors with my code, so I have a lot of console.logs. Here are the console.logs when the code successfully works.

 cookie set
 Document is Invoice (Invoice)
 Invoice order #: ORD83001
 Current ID: 52724 Order #: ORD83001
 cookie set
 Document is DELIVERY SLIP (DELIVERY SLIP)
 Invoice order #: ORD83001
 DELIVERY SLIP Doc ID: 52553
 Current ID: 52553 Order #: ORD83001
 Full id func: 52553,ORD83001
 id[0]: 52553
 New Tray Doc ID: 1410
 Document's successfully merged.

Now, with the error, the console.logs are:

 //.....
 Current ID: 0 Order #: ORD83009
 Full id func: 0,ORD83009
 id[0]: 0
 id[0]: 0
 Document's successfully merged.

The thing about this error, is that if id[0] was truly zero, then the document’s wouldn’t be able to be merged. But the documents ARE merged if I look at them. So why is my code returning 0, even INSIDE my if statement, yet continues to run?

Is it some sort of timing issue? Like id[0] === 0 but .00000001 seconds later it gets updated so the return null doesn’t follow through?

Angular Electron not working on first load

I have tried building an Angular application with Electron and I have the following issue: When the app starts, the browser window is empty, nothing in the console. The whole body tag is empty as well. However, after I manually press reload in the Electron browser, it works – everything runs as expected. Any ideas why this might happen?

This is my main.js file:

const {app, BrowserWindow} = require('electron');
const {autoUpdater} = require("electron-updater");
const log = require('electron-log');

const url = require("url");
const path = require("path");
var webpackTargetElectronRenderer = require('webpack-target-electron-renderer');


autoUpdater.logger = log;
autoUpdater.logger.transports.file.level = 'info';
log.info('App starting...');

let win;

function sendStatusToWindow(text) {
  log.info(text);
  console.log(text);
  mainWindow.console.log(text);
  win.webContents.send('message', text);
}
// function createDefaultWindow() {
//   win = new BrowserWindow();
//   win.webContents.openDevTools();
//   win.on('closed', () => {
//     win = null;
//   });
//   win.loadURL(`file://${__dirname}/version.html#v${app.getVersion()}`);
//   return win;
// }

app.on('certificate-error', (event, webContents, url, error, certificate, callback) => {
  // On certificate error we disable default behaviour (stop loading the page)
  // and we then say "it is all fine - true" to the callback
  console.log(JSON.stringify(certificate));
  event.preventDefault();
  callback(true);
});

let mainWindow


var options = {
  // webPreferences: {
  //   webSecurity: false
  // },
  node: {
    __dirname: false
  }
}

options.target = webpackTargetElectronRenderer(options)

function createWindow () {
  mainWindow = new BrowserWindow({
    width: 1000,
    height: 800,
    webPreferences: {
      nodeIntegration: true
    }
    // webPreferences: {
      // plugins: true,
      // nodeIntegration: true,
      // webSecurity: false
    // }
  })

  // log.info('Hello, log');
  // log.info(log.transports.console);
  // console.log(log.transports.console);
  // log.warn('Some problem appears');
  // // log.info("Test");
  // console.log = log.info;
  console.log("TEst");
  // log.info(log.transports.file.getFile());
  mainWindow.loadURL(
    url.format({
      pathname: path.join(__dirname, `/dist/index.html`),
      protocol: "file:", 
      slashes: true
    })
  );
  // mainWindow.webContents.devToolsWebContents("Test");
  // var x = path.join(__dirname, `/dist/index.html`);
  // console.log(x);
  // mainWindow.loadURL(`file://${__dirname}/version.html#v${app.getVersion()}`);

  // Open the DevTools.
  mainWindow.webContents.openDevTools();
  // console.log("Test");

  mainWindow.on('closed', function () {
    mainWindow = null
  })

  autoUpdater.on('checking-for-update', () => {
    sendStatusToWindow('Checking for update...');
  })
  autoUpdater.on('update-available', (ev, info) => {
    sendStatusToWindow('Update available.');
  })
  autoUpdater.on('update-not-available', (ev, info) => {
    sendStatusToWindow('Update not available.');
  })
  autoUpdater.on('error', (ev, err) => {
    sendStatusToWindow('Error in auto-updater.');
  })
  autoUpdater.on('download-progress', (ev, progressObj) => {
    sendStatusToWindow('Download progress...');
  })
  autoUpdater.on('update-downloaded', (ev, info) => {
    sendStatusToWindow('Update downloaded; will install in 5 seconds');
  });

}

// app.on('ready', createWindow)
app.on('ready', function()  {
  createWindow();
  autoUpdater.checkForUpdatesAndNotify();
});

app.on('window-all-closed', function () {
  if (process.platform !== 'darwin') app.quit()
})

app.on('activate', function () {
  if (mainWindow === null) createWindow()
})