How to pass a class type as parameter?

As described here: Declare class type with TypeScript (pass class as parameter) i can pass a class type as parameter.

There is a problem.

export namespace customCommand {
    export class Command {
        public constructor(parameter?: any) {

        }
    }

    export function register(command: typeof Command) {

    }
}

When i do this

customCommand.register(Map)

or

customCommand.register(Object)

There is no errors. I know that typeof Command and typeof Map both return the same result.

But how can i protect this and pass only Command type?

FirebaseError: Expected type ‘Pc’, but it was: a function

I’m trying to add a document inside a subcollection inside an already existing document. When the function runs, I keep getting this error saying: FirebaseError: Expected type ‘Pc’, but it was: a function.

Code:

const docRef = doc(db, "user", data.id);
const colRef = collection(docRef, 'teams')
addDoc(colRef, {
   id: response.data.account.id,
   role: 'owner',
   uid: data.id,
});

image doesn’t render when using next.js Image tag

I have an image located in the public/img directory. I want to render it using the next.js built-in <Image/> tag.

here is the code I have written:

     <Image
                onClick={hideModal}
                alt="close_button"
                src="/img/close_button.png"
                width="20px"
                height="20px"
              />

but nothing is shown on the page (not even the alt-text).

the thing is when I use the <img/> tag, it works as expected but with the <Image/>, it doesn’t

Why does one use the const keyword for functions? [closed]

Keywords convey meaning. In most programming languages, the keyword for denoting a constant is usually used just for that. So consider the following two almost-equivalent statements in JavaScript:

  • const foo = (a, b) => return a + b
  • function foo(a, b) { return a + b }

Why on Earth would one choose the former? Is it just popularity? I find the latter so much easier to read. E.g. when looking through code, by using the function keyword, I immediately realize that it is a function. When using const however, my eyes must also scan for a lambda, because people use the const keyword for pretty much everything these days.

Or is there some convincing argument to use const?

Construct MongoDB query from GraphQL request

Let’s say we query the server with this request, we only want to get the following user’s Email, My current implementation requests the whole User object from the MongoDB, which I can imagine is extremely inefficient.

GQL
{
  user(id:"34567345637456") {
    email
  }
}

How would you go about creating a MongoDB filter that would only return those Specified Fields? E.g,

JS object
{
   "email": 1
}

My current server is running Node.js, Fastify and Mercurius

Javascript + Rest + Google Chart: g is undefined

I am coding a website getting data from an home made API and publishing that on a google chart.

on my chart area, I get a text or a red background “g is undefined”.

It is driving me crazy, any clue of what I am doing wrong?

google.charts.setOnLoadCallback(drawChart);
var chart

function drawChart() {

    var data = new google.visualization.DataTable();
    data.addColumn('string', 'Date');
    data.addColumn('number', 'Positive');
    data.addColumn('number', 'Negative');
    data.addColumn('number', 'Mixed');
    data.addColumn('number', 'Neutral');

    var request = new XMLHttpRequest()

    // Open a new connection, using the GET request on the URL endpoint
    request.open("POST", apiEndPoint + "/dailystats", true);
    request.setRequestHeader('Content-Type', 'application/json');
    request.send(JSON.stringify({"media":media,"period":parseInt(period)}));


    request.onload = function() {
    var restcall = JSON.parse(this.response)
        if (request.status >= 200 && request.status < 400) {
            restcall.forEach(metric => {
                data.addRows([[metric.date,metric.sentiments.positive,metric.sentiments.mixed,metric.sentiments.neutral,metric.sentiments.negative]])
            })
        }
    }
    var options = {
    chart: {
        title: 'Box Office Earnings in First Two Weeks of Opening',
        subtitle: 'in millions of dollars (USD)'
    },
    width: 900,
    height: 500
    };

    chart = new google.charts.Line(document.getElementById('linechart_frame'));

    chart.draw(data, google.charts.Line.convertOptions(options));
}```

Thanks!

Creating a Filters organism in Storybook [with React]

I’ve been trying to resolve this task for the last few days, but holy moly I’ve been running in circles with every solution I could think of. Right now I feel drained and I’m in serious need of help.

To give a bit of background, we use Storybook at work. I’m supposed to create this Filter organism, which could have the following structure that was suggested by another developer.

<FilterBar onRemove onAdd onChange>
  <FilterBarItem optional={ false } onChange>
    <Dropdown />
  </FilterBarItem>
  <FilterBarItem optional={ true } onChange>
    <TextField />
  </FilterBarItem>
  <FilterBarItem optional={ true } onChange>
    <TextField />
  </FilterBarItem>
  <FilterBarSelect onChange>
    <Dropdown />
  </FilterBarSelect>
</FilterBar>

First of all, let me try to explain how this should work, at least from my understanding (still not 100% clear on what we’re trying to achieve, but I guess we can take any other e-commerce filter out there as example).

So the user can add or remove filters to narrow down a list of products to their preference. Each filter also have a few options to choose from. For example:
Let’s say I’m looking for white shoes size 41 on a website. I’m going to apply the size filter (which should have some options), I’m going to apply a color filter maybe, and some type of footwear I want (shoes).

Coming back to our structure.

FilterBar I suppose it’s going to be the main wrapper and the one that controls if we add or remove filters.

FilterBarItem is going to be the filter itself and now, here’s the first challenge. It doesn’t know which type of child component it’s gonna have, it can be a dropdown of options, it can be a color picker, it can be a normal input field where user can input something, etc.

FilterBarSelection is going to be a styled dropdown, based on the react-select library and it’s going to have some filters options passed in and based on what it’s selected, it will generate a new FilterBarItem.

Ok here’s how I thought about implementing this and what are the issues.

The FilterBar

const FilterBar = ({ children, ...props }) => {
 // Maybe here we can add the array of options we want to pass into FilterBarSelection?
 // Also maybe here too we want to create the onAdd, onRemove functions and pass them into whatever component needs it? For example, onRemove should be passed into the FilterBarItem and the onAdd should be passed into FilterBarSelection since it's the one that controls how many filters we apply?
 // Also if we have a list of filters that can't be removed by the user, I'm guessing they also have to be added here?
 return (
  <div className="someClass">
   <div className="mandatory-filters">
    { children }
   </div>
   <div className="optional-filters">
  { React.Children.map(children, child => (
      React.cloneElement(child, { onAdd={ }, onRemove={ }, ...props }))) }
   </div>
  </div>
 )
}

The FilterBarItem

const FilterBarItem = ({ optional, children }) => {
 // If the filter is optional, then we want to have the ability to remove the filter if the user decides to.
 if(optional) {
   return (
    <>
    { children } // can we determine the type of filter we want to add? For example, like I said before, it can be a simple input
    <button onClick={ onRemove }>Remove</button>
    </>
   )
 }

 return (
  <>
   { children }
  </>
 )
}

The FilterBarSelection

const FilterBarSelection = () => {
 return (
  <ReactSelect 
    isMulti 
    options={ filterOptions } />
 )
}

As you can see, there are a lot of problems I don’t know how to fix. And this is why I needed some help with the implementation because honestly I’ve ran out of ideas.

How can I convert a plain array into an array with objects?

in my vuejs project I’m working on, the information from the api comes in the form of a flat array. I need to edit this incoming data and convert it to the following format.
For example, I need to arrange the parent id of an object to be the id of its parent item.

How can I solve this problem, I am waiting for your ideas.

data from api

{
  "id": 1,
  "parentId": 0,
}, {
  "id": 2,
  "parentId": 0,
}, {
  "id": 3,
  "parentId": 0,
}, {
  "id": 4,
  "parentId": 3,
}, {
  "id": 5,
  "parentId": 3,
}, {
  "id": 6,
  "parentId": 4,
}, {
  "id": 7,
  "parentId": 4,
}, {
  "id": 8,
  "parentId": 5,
}, {
  "id": 9,
  "parentId": 5,
}, {
  "id": 10,
  "parentId": 0,
}

this is how i want to edit data

items: [{
    id: 1,
    parentId: 0,
    children: [{
      id: 10,
      parentId: 1,
    }, ],
    id: 2,
    parentId: 0,
    children: [],
    id: 3,
    parentId: 0,
    children: [{
        id: 4,
        parentId: 3,
        children: [{
            id: 6,
            parentId: 4,
            children: [],
          },
          {
            id: 7,
            parentId: 4,
            children: [],
          },
          {
            id: 8,
            parentId: 4,
            children: [],
          },
        ],
      },
      {
        id: 5,
        parentId: 3,
        children: [{
            id: 9,
            parentId: 5,
            children: [],
          },
          {
            id: 10,
            parentId: 5,
            children: [],
          },
          {
            id: 11,
            parentId: 5,
            children: [],
          },
        ],
      },
    ],
  }, ],

Authentication and authorization using Cookies with React+Redux and ExpressJS

so I am writing an app and for a couple of days I struggle to proplerly authenticate and authorize user.
My express config:

const cookieLifetime = 1000 * 200;
app.use(
  cors({
    origin: "http://localhost:3000",
    methods: ["GET,PUT,POST,DELETE,PATCH,OPTIONS"],
    credentials: true,
    allowedHeaders: `Content-Type, Authorization, X-Requested-With`,
  })
);

app.use(
  session({
    name: `cookie`,
    resave: false,
    saveUninitialized: false,
    store: store,
    secret: `secretttttttt`,
    cookie: {
      secure: false,
      maxAge: cookieLifetime,
      httpOnly: false,
      sameSite: false,
    },
  })
);

Login route

router.post(`/login`, async (req, res) => {
  try {
    const user = await User.findByCredentials(req.body.email, req.body.password);
    if (!user) {
      req.session.error = `Niepoprawny adres email lub hasło`;
      res.status(404).send(req.session.error);
    }
    req.session.user = user;
    res.status(200).send(req.session);
  } catch (e) {
    res.status(404).send();
  }
});

As far everything is working correctly. I would like to add a couple of protected routes, so I am using auth middleware in route, which looks

const isAuth = (req, res, next) => {
  console.log(req.cookies);
  if (req.cookies.cookie) {   
    next();
  } else {
    req.session.error = "Musisz być zalogowany, aby wykonać tą operacje";
    res.status(400).send(req);
  }
};

module.exports = isAuth;

In my front I would like to login user and then check if user is logged in to access routes, I think my idea of routing is decent but here is how it looks

const Login = () => {
  const dispatch = useDispatch();
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [loading, setLoading] = useState(null);
  const navigate = useNavigate();

  const user = useSelector((state) => state);

  const fetchData = () => {
    dispatch(loginUser({ email, password }));
    setLoading(true);
  };

  const handleFormSubmit = (e) => {
    e.preventDefault();
    fetchData();
  };

  useEffect(() => {
    if (user.user !== null && loading === true) {
      setLoading(false);
      if(user.user.userRole === "reviewer"){
        navigate("/reviewerView", { replace: true });
      } else {
        navigate("/appView", { replace: true });
      }
    }
  }, [user]);

Now finally my final route, which I would like to check if user is logged in based on cookies.

export const PostList = () => {
  const dispatch = useDispatch();
  const [isLoading, setIsLoading] = useState(null);
  const [selectedTopic, setSelectedTopic] = useState("");
  const posts = useSelector((state) => state.post);
  const cookie = Cookies.get("cookie");

  useEffect(() => {
    if ( cookie !== undefined && (posts.length === 0 || posts === undefined)) {
      setIsLoading(true);
      dispatch(getPosts());
    }
    if (posts.posts !== undefined) {
      setIsLoading(false);
    }
  }, [posts, cookie]);

My question is – is my approach correct ? If not what and how can I change it to make it work and look properly ?

JavaScript Edit Website (Specific button doesn’t work like i want to)

I created a script for Tampermonkey to edit every Website, now I want to have, that this button right above the caps lock: –>| (on Mac) switches between buttons when I click on it. Currently it puts some spaces between the words, but that’s what i don’t want. Here’s my script:

     // ==UserScript==
// @name         Edit any Website
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  try to take over the world!
// @author       You
// @match      *://*/*
// @icon         data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==
// @grant        none
// ==/UserScript==
(function () {
    'use strict';
    // javascript:document.body.contentEditable = 'true' ;
    document.designMode = 'on';

    document.querySelectorAll('a').forEach((a) => {
        a.addEventListener('click', (e) => {
            location = e.currentTarget.href;
        })
    })
    })();

Can someone help me?

How to throw an error from API and catch it from client side?

I have two different projects. First one is the outer shell of the site, basically html+js. There is a registration function where you send data in the POST array:

const registerUser = async function(e) {
 e.preventDefault();

 let email = document.querySelector('#email').value;
 let password = document.querySelector('#password').value;
 let confirmPassword = document.querySelector('#confirm_password').value;

 const formData = new FormData();
 formData.append('email', email);
 formData.append('password', password);
 formData.append('confirm_password', confirmPassword);

 try {
   await fetch(`${API}/users`, {
   method: 'POST',
   body: formData,
   }).then((response) => {
     email = '';
     password = '';
     confirmPassword = '';
     console.log(response);
   })
 }
 catch(err) {
   console.log(err);
 }
}

The second one is a simple REST API on PHP where client side sends data to. It receives the POST array and registers the user.

function registerUser($db, $postData) {
 $email = mysqli_real_escape_string($db, $postData["email"]);
 $password = mysqli_real_escape_string($db, $postData["password"]);
 $confirm_password = mysqli_real_escape_string($db, $postData["confirm_password"]);

 if(empty($postData) || !isset($email) || empty($email) || !isset($password) || empty($password) 
 || !isset($confirm_password) || empty($confirm_password)) return false;

 if($password !== $confirm_password) {
   $_SESSION["error"] = "Passwords don't match!";
   return false;
 }

 $user = mysqliQuery($db, "SELECT * FROM `users` WHERE `email` = '$email';");

 if(mysqli_num_rows($user) > 0) {
   $_SESSION["error"] = 'User with such email already exists!';
   return false;
 };

 $date = date("Y-m-d H:i:s");
 $hashPass = password_hash($password, PASSWORD_DEFAULT);
 $nameFromEmail = strstr($email, '@', true); 

 if(mysqliQuery($db, "INSERT INTO `users` (`id`, `email`, `password`, `registered_at`, `name`) 
 VALUES (NULL, '$email', '$hashPass', '$date', '$nameFromEmail');")) {
   http_response_code(201);
 }

 else {
   http_response_code(401);
 }
}

But the problem is, I don’t know how to throw an error if received email already exists in the database. Is there any way to send an error from PHP server side in response to client side after fetching?

Can I use preventDefault to my event with passive equal true?

I’ve came across to the next article, there I found example with blocking scroll event:

document.body.addEventListener('pointermove', event => {
  if (event.cancelable) {
      event.preventDefault(); // block the native scroll
      /*
      *  do what you want the application to do here
      */
  }
}, {passive: true});

but, it doesn’t work, by the way I see illogicality using preventDefault in passive: true event. What is going on, anyone would explain to me?

How to replace query parameter only if it exists using string replace All regex

I have following urls :

https://test1.com/path?query1=value1

and

https://test2.com/path

I am trying to add additional query param to all urls, so i am trying something like

url.replaceAll(/(.*)[?]?(.*)/g,"$1?newquery=newvalue&$2")

let url = "https://test1.com/path?query1=value1"
console.log(url.replaceAll(/^(.*)[?]?(.*)$/g,"$1?newquery=newvalue&$2"))
url = "https://test1.com/path"
console.log(url.replaceAll(/^(.*)[?]?(.*)$/g,"$1?newquery=newvalue&$2"))

But it doesnt work as expected , could someone shed some light

Connect to game server using Discord Embed

I am trying to send a message to a channel when a client executes a specific slash command.
The command should send a embed that will contain a field. I want to make that field “clickable” so that people can join.

I want them to join a steam game server (CS:GO) that uses the protocol steam://connect/ip:port/password to connect.

I tried the following to send the message:

const { SlashCommandBuilder } = require('@discordjs/builders');
const { MessageEmbed } = require('discord.js');

module.exports = {
    data: new SlashCommandBuilder()
        .setName('stackoverflow')
        .setDescription('Question to stackoverflow'),

    async execute(interaction) {
        const embed = new MessageEmbed()
            .setColor('#ff0000')
            .setTitle('test')
            .setAuthor({ 
                name: 'Test'
            })
            .setDescription('Testing')
            .addField('Click below to join the server', '[Click here](steam://node1.spirtshop.cf:6002/TestesNexus!2022)')
            .addFields(
                { name: 'u200b', value: '[Join the server](steam://node1.spirtshop.cf:6002/TestesNexus!2022)'},
                { name: 'Connect through the console', value: 'connect node1.spirtshop.cf:6002; password TestesNexus!2022'}
            )
            .setTimestamp()
            .setFooter({
                 text: 'Just testing'
            });
        await interaction.reply({embeds: });
    },
};

Unfortunately, this doesn’t work: (output) -> https://i.imgur.com/D4xCCVm.png

I’ve found some bots written in python, however, I couldn’t take that into NodeJS. In my interpretation Discord just recognizes as a “clickable link” if I send it as the protocol(?).

The expected result is something like this: https://i.imgur.com/UcERDcM.png

From that screen shot, I just want to replace the steam://…. with some text.

Any idea of how I can make this?

(using nodejs v17.4.0, discordjs v13.6.0)