How to get price from checkout page/DOM securely

am a beginner and i need help in integrating paypal. Am using node.js and ejs template engine for my project. I am trying to get price from DOM and sending it to nodejs route in post request. I want to find a secure way to get price from dom so user can’t change it using html inspector.

Right now am getting package id from url and sending it inside body of request and then finding the price in database. For quantity am getting it from dom and sending it in request body.

I need to implement discount voucher functionality what’s the best practices to get these values from DOM?

Promise not completing on rejection

So I have a form that submits with the following function:

const formSubmit = async (formData) => {
  const response = await SubmissionsResource.create(formData)
  const { data, status } = response
  console.log('Request completed.')
  if (status === 201) {
    toast.success('Submission created.')
  } else {
    toast.error('Something went wrong.')
    console.error(data)
  }
}

Which uses the following:

const SubmissionsResource = {
  create: ({ formData }) => (
    Request.privatePost(apiUrl('submissions'), formData)
  ),
}

Which uses the following:

export const Request = {
  privateRequest: ({ data, method, params, url }) => {
    axios.interceptors.request.use((request) => {
      request.headers.authorization = getBearerToken()
      return request
    }, (error) => Promise.reject(error))

    axios.interceptors.response.use(
      (response) => response,
      async (error) => {
        const originalRequest = error.config

        // If request is coming from a sign in attempt
        if (error.response.status === 401 && originalRequest.url.includes('auth/token')) {
          return Promise.reject(error)
        }

        // If request is coming from elsewhere, assume token might be expired
        if (error.response.status === 401 && !originalRequest._retry) {
          originalRequest._retry = true
          const refresh_token = LocalStorageService.getRefreshToken()
          const response = await axios.post(
            `${API_BASE}/oauth/token`,
            { client_id, client_secret, grant_type: 'refresh_token', refresh_token }
          )
          if (response.status === 200) {
            LocalStorageService.setUser(response.data)
            axios.defaults.headers.common.Authorization = getBearerToken()
            return axios(originalRequest)
          }
          return Promise.reject(error)
        }
        return Promise.reject(error)
      }
    )
    return axios({ method, url, data, params })
  },
  privatePost: (url, data) => (
    Request.privateRequest({ method: 'post', data, url })
  )
}

When the response is successful, I always see the “Request completed” log, and I see the toast.success message. However, when the request fails, I never see the “Request completed” log, nor the toast.error message.

The axios interceptor should retry once if the response comes back unauthorized (401 status code), which it successfully does, and in all other cases, reject the promise and return the error.

Request.privateRequest should reject the promise and return the error to Request.privatePost, which should return back to SubmissionsResource.create, and then finally to formSubmit. However, instead of completing the promise and returning an error, it just halts the entire function and doesn’t ever get to the “Request completed” log.

I’m assuming this is due to an incorrect understanding with promises on my end, but I can’t figure out what that is. Why isn’t the promise being completed and continuing on to the next line within formSubmit?

How do I read from a file in PHP and complete the action in JavaScript/CSS?

Let’s say I have 2 boxes and a text file called data.txt:

<?php 
    $myfile = fopen("data.txt") or die("Unable to open file");
 ?>
<button> Go </button>
<div id = "box1" >
    <h5> BOX 1 </h5>
<?php echo fread($myfile,filesize("data.txt")); ?>
</div>

<div id = "box2>
<h5> BOX 2 </h5>
</div>
#box1 {
      width: 100px;
      height: 200px;
      background-color: red;
      position: absolute;
      left: 0px;
      top: 0px;
      text-align: center;
      font-family: Times New Roman;
    }

#box2 {
      width: 100px;
      height: 200px;
      background-color: white;
      position: absolute;
      left: 0px;
      top: 0px;
      text-align: center;
      font-family: Times New Roman;
    }

How do I move the text from the text file, “Hello World” from box 1 to box 2 using plain JavaScript?

Generating an auto increment document code

I’m working on a system where I’ll need to be able to generate a serial number for a bunch of documents in javascript, they need to be on the [number]/[date] format, so 001/2022, 002/2022 and so on. The thing is that I already know how to generate the first part of it, but I’m having trouble keeping the date consistent. I tried to use Date().getCurrentYear() but I’m not having the desired result.

MUI slider not draggable more than one step at a time

So I have a mui slider on my map that changes the year of display data for a specific Layer. However my Mui slider is not “draggable” it only lets me move one step at a time then stops and I have to let go of the slider and then redrag it. Clicking around on it works fine. When setYear changes it runs a function in usememo that changes the layer. I suspect this might be the problem but have can I avoid it?

const handleTimeChange = (event, newValue) => {
    if (newValue !== year) {
      setYear(newValue);
    }
  };
<Slider
        getAriaLabel={() => "Date range"}
        value={year}
        onChange={handleTimeChange}
        valueLabelDisplay="auto"
        sx={{ width: "200px", ml: "20px" }}
        max={2020}
        min={min}
        align="center"
      />

How can I pass props to inner React component using functional approach

I am using react with the following functional approach

const Divider: React.FunctionComponent = (props: CardDividerProps) => (
   <div>
      divider
   </div>
);

const Card: React.FunctionComponent = (props: CardProps) => {
 const color = props.color

 return(
   <div>
      card
   </div>
 )}

Card.Divider = Divider;

and I call these components as following

<Card color="red">
 <Card.Divider>
  Any text
 <Card.Divider/>
<Card />

The problem is: How can I get the color props in the Divider component

PS: I don’t want to repeat props passing again for divider like following

<Card color="red">
 <Card.Divider color="red">
  Any text
 <Card.Divider/>
<Card />

Why image doesn’t center in ?

so i am building a web-app with google script and the result is a dashboard with several tables. I am also using bootstrap (https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css).
I’ve been looking for an answer for long days but i just can’t find out what i am missing.

So in a table, i want to insert an image that has to be centered horizontally and vertically, in the center of the td and has to fit and adapt to the row or td height i’ll choose.

But again and again, my image goes to the bottom of the td/row and often overlaps and below the row, it seems to have the right height, but it never places itself correctly. I have made a copy of little portion of my code to make it clearer:

Here the result i get

And here is my code:

<div class="row" style="width: 500px"> <!-- TABLE TEST -->
        <div > <!-- Test -->
          <table class="table">
            <thead>
              <tr>
                  <th>Rank</th>
                  <th>Name</th>
                  <th>Points</th>
              </tr>
            </thead>
            <tbody>
              <tr><td>1</td><td><img src="https://static.sky.it/images/skytg24/it/spettacolo/serie-tv/2021/02/25/spongebob-serie-tv-kamp-koral/kamp.jpg"></td><td>3</td></tr>
              <tr><td>11</td><td><img src="https://static.sky.it/images/skytg24/it/spettacolo/serie-tv/2021/02/25/spongebob-serie-tv-kamp-koral/kamp.jpg"></td><td>33</td></tr>
              <tr><td>111</td><td><img src="https://static.sky.it/images/skytg24/it/spettacolo/serie-tv/2021/02/25/spongebob-serie-tv-kamp-koral/kamp.jpg"></td><td>333</td></tr>
            </tbody>
          </table>
        </div> <!-- CLOSE TABLE TEST -->

I also paste here my page.css code:

<style>
  .row {
  }

  table {
    text-align: center;
  }  

  tr {
    line-height: 20px;
  }
  
  th, td {
    position:relative;
    text-align:center;
    vertical-align:middle;
  }

  img {
    display: block;
    vertical-align: center;
    position:absolute;
    height:20px;
  }
  </style>

I have tried what i found around: display:block, position:relative for parents, absolute for childs, and several other solutions, but nothing seems to work.
I am clearly missing something and i probably have messed with the styles so much that i even might have tried the good solution which might have been blocked by other mistakes.

Thanks to who might help

Javascript is it bad practice to return an object that is passed by reference

Let’s say I have this function in javascript:

function foo(a){
    a.item = "four"
    return a
}

b = {item:"three"}
b = foo(b)
console.log(b)

Since Javascript is a call-by-sharing language there is no need to return a, the object b would have the same final value with the below code:

function foo(a){
    a.item = "four"
    return a
}

b = {item:"three"}
foo(b)
console.log(b)

Is it bad practice to use return b for better readability even though it is not needed

Are there any downsides to returning the object?

Mongoose append element to array if doesn’t exist remove if it does

I have a user model that can have an array of images;

const UserSchema = new mongoose.Schema({
  email: {
    type: String
  },
  password: {
    type: String
  },
    favorites:[imageschema]
});

I have a button on my frontend that I need to toggle the “favorite” status of the image; i.e. have it present in the “favorites” array of my user.

So essentially I want to get the user and then I want it to remove the image from the favorites array if its present in it, add it to the array if its not.

Assuming I use my user’s email address to find his/her document like so;

User.Find({email:email}).exec.then(...)

What do I need to add to accomplish this?

Is Strapi or Notion good products to use to create a full stack application with Users

I am looking to create an investment application for a client which would have Offerings (a deal that you can invest in), Investments (payments that the investor makes to buy into the investment), and Investors (users)

The Investor would be able to see all of the Offerings and all of the Investments that they have made.

I was looking into Strapi and Notion.

Strapi, I found useful because there is a relational db and it has a way to authenticate a user and fetch and update all individual user data.

Notion also has a great way to set up a relational db but I have not been able to figure out how a user would be able to authenticate and fetch and modify only the signed in users information.

Can anyone offer some sort of solution for Notion? I am also open to other products if there are better solutions out there.

Fetch is not Defined

I’m very new to Javascript and just built my very first bot, I try to run my bot and it WORKS! But when I use the discord command it crashes on Replit :(. I have done npm install node-fetch but that doesnt seem to be working aswell. I am depsperate in finishing my first bot please help.
Here is the error:

/home/runner/myrepl/index.js:52
    fetch(`https://www.rolimons.com/uaid/` + id).then(res => res.text()).then(res => {
    ^

ReferenceError: fetch is not defined
    at Client.<anonymous> (/home/runner/Poisithink/index.js:52:5)
    at Client.emit (node:events:390:28)
    at Client.emit (node:domain:475:12)
    at MessageCreateAction.handle (/home/runner/Poisithink/node_modules/discord.js/src/client/actions/MessageCreate.js:26:14)
    at Object.module.exports [as MESSAGE_CREATE] (/home/runner/Poisithink/node_modules/discord.js/src/client/websocket/handlers/MESSAGE_CREATE.js:4:32)
    at WebSocketManager.handlePacket (/home/runner/Poisithink/node_modules/discord.js/src/client/websocket/WebSocketManager.js:351:31)
    at WebSocketShard.onPacket (/home/runner/Poisithink/node_modules/discord.js/src/client/websocket/WebSocketShard.js:444:22)
    at WebSocketShard.onMessage (/home/runner/Poisithink/node_modules/discord.js/src/client/websocket/WebSocketShard.js:301:10)
    at WebSocket.onMessage (/home/runner/myrepl/node_modules/ws/lib/event-target.js:199:18)
repl process died unexpectedly: exit status 1

My Index.js is:

const { Client, Intents } = require('discord.js');
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] });
const { token } = require("./token.json");
var jsonconfig = require("./config.json")
var jsonconfig,DISCORD_ID
var CMDS = jsonconfig.CMDS

client
    .login(token);

var prefix = '$'
client.on("messageCreate", message => {
  console.log('Ready!');
var args = message.content.split(" ")
args.forEach((a, b) => {
  args[b] = a.replace("`", "")

  args[b] = args[b].replace(".", "")

  args[b] = args[b].replace("`", "")
  args[b] = args[b].replace(`"`, "")

  args[b] = args[b].replace(`'`, "")

})
var args = message.content.split(" ")
if (message.author.bot == false) {
  if (message.content.startsWith("$")) {

    if (message.channel.id != CMDS && message.author.id != DISCORD_ID) {
      message.reply("stop using cmds here idiot. <#" + CMDS + ">")
      return;
    }
  }

  args.forEach((a, b) => {
    args[b] = a.replace("`", "")
    
    args[b] = args[b].replace(".", "")

    args[b] = args[b].replace("`", "")
    args[b] = args[b].replace(`"`, "")

    args[b] = args[b].replace(`'`, "")

        })
  switch (args[0]) {
    
    case prefix + "pois":
  var id = parseInt(args[1])
  if (id) {
    fetch(`https://www.rolimons.com/uaid/` + id).then(res => res.text()).then(res => {
      //// clog(res)
      if (res != 'Uaid not found, try again later') {
        var search = res,
          first = 'uaid_details'
        var second = `owner_list`;
        var itemdat = JSON.parse(search.substring(search.indexOf(first) + first.length, search.indexOf(second)).replace(";", "").replace("=", "").replace("var", ''))
        // clog(itemdat)
        var search = res,
          first = 'item_details'
        var second = `uaid_details`;
        var itemname = JSON.parse(search.substring(search.indexOf(first) + first.length, search.indexOf(second)).replace(";", "").replace("=", "").replace("var", ''))
        var search = res,
          first = 'owner_list'
        var second = `lucky_cat_uaid`;
        var owners = JSON.parse(search.substring(search.indexOf(first) + first.length, search.indexOf(second)).replace(";", "").replace("=", "").replace("var", ''))
        message.reply(`Checking be patient bozo...`)
        var em = new discord.messageEmbed()
        .setFooter("Archs")
      .setURL("https://www.rolimons.com/item/" + args[1])
        .setColor("#ffc0cb")
        .setThumbnail("https://www.roblox.com/thumbs/asset.ashx?width=420&height=420&assetid=" + itemdat["asset_id"])
        .setTitle(`UAID ` + args[1])
        .setURL(`https://www.rolimons.com/uaid/` + args[1])
        .setAuthor(itemname.name, `https://www.roblox.com/thumbs/asset.ashx?width=420&height=420&assetid=` + itemdat["asset_id"])
      if (itemdat.serial) {
        em.addField('SERIAL', itemdat.serial)
          }
        em.addField('OWNER', (itemdat.owner_name || `Hidden/Deleted`))
        em.addField(`Last Traded`, itemdat["updated_relative_string"])
        message.reply(em)
        if (itemdat["updated_relative_string"].search(`month`) != -1 || itemdat["updated_relative_string"].search(`year`) != -1) {
          message.channel.send(`Since the current owner has had it for more than a month, we have deemed this uaid(${args[1]}) as CLEAN :white_check_mark:`)
          } else {
          comped_detected = false
          Object.keys(owners).forEach(x => {
            var item = owners[x][0]
            if (item && parseInt(x) + 2628000 >= Date.now() / 1000) {
              fetch(`https://avatar.roblox.com/v1/users/${item}/avatar`).then(res => res.json().catch(err => { })).then(avatar => {
                avatar.assets.forEach(a => {
                  if (badassets[a.id] != undefined) {
                    comped_detected = true
                                                            }
                })
                fetch("https://inventory.roblox.com/v1/users/" + item + "/assets/collectibles?sortOrder=Asc&limit=100").then(res => res.json().catch(err => { })).then(p => {
                  // clog(p)
                  var amt = 0
                  if (p.data) {
                    p.data.forEach(l => {
                      amt = amt + itemdata[l.assetId][4]
                      })
                    if (amt < 5000) {
                      comped_detected = true
                    }
                  }
                })
              })
            }
          })
        }
      }
    }
  )}
  }
}
})

Please help I am SO SO CLOSE to finishing my very first discord bot!!! Any help is appreciated.

Method/pattern to check for children accounts and place them as nested objects

I have an account object with children accounts (rootAccount). I am trying to write some logic that will take the rootAccount object and search the children accounts to see if they are parents of any accounts. If so, then those accounts will be added to the children account in a new property for the account called children. It becomes a little more complex because each new account can possibly have child accounts and likewise be added as a new property to the account. So this will keep nesting objects possibly until there are no more children accounts.

Is there a common pattern/method to use for this scenario? I can get about as far filtering out the object that is the parent but I’m not sure how to add it to the rootAccount object and then loop this logic so it will check for new children accounts and keep adding nested children accounts.

   var childAccount = [{Name: "Johnson Little Plastics", Id: '4', parentAccount: '3'}];


   var rootAccount = {
     Name: "Johnson Holding Company",
     Id: '1',
     children: [
       {Name: "Johnson Metals", Id: '2', parentAccount: '1'},
       {Name: "Johnson Plastics", Id: '3', parentAccount: '1'}
       ]
     }


     for(var x of childAccount){
         var f = rootAccount.children.filter((account,i) => {
         return account.Id == x.parentAccount;
     });

     console.log(f[0].Id);
     }

What it will look like after it runs through:

   var rootAccount = {
     Name: "Johnson Holding Company",
     Id: '1',
     children: [
       {Name: "Johnson Metals", Id: '2', parentAccount: '1'},
       {Name: "Johnson Plastics", Id: '3', parentAccount: '1',
        children: [{Name: "Johnson Little Plastics", Id: '4', parentAccount: '3'}]
       }
       ]
     }

How to put inside a svg

Is there a way to put a div inside a path?

It works fine with rect

<svg viewBox="0 0 200 200" xmlns="http://www.w3.org/2000/svg">
    <rect class="bg" id="bg" x="0" y="0" width="200" height="200" fill="#0357D5"></rect>
    <foreignObject x="0" y="0" width="60" height="50">
        <div xmlns="http://www.w3.org/1999/xhtml">Thanks </div>
    </foreignObject>
</svg>

but not with path

<svg viewBox="0 0 200 200" xmlns="http://www.w3.org/2000/svg">
    <path class="pth" id="pth" d="M0,0, L200,0, L200,2000, L0,200 ,Z" fill="red"
            style="stroke-width: 0.5; stroke: red;">
    <foreignObject x="10" y="50" width="60" height="50">
        <div xmlns="http://www.w3.org/1999/xhtml">Thanks </div>
    </foreignObject>
</svg>

Is there a way to achieve this?