zohoorparvaz
zohoorparvaz

Reputation: 15

export input query from one GET request and use them on separate requests

I am trying to use the input of the user on my RESTful API in the query for one GET request and use that data to randomize a number and use that info for the rest of the application. any guidance about best solution to store the values and use them on different blocks throughout the application is appreciated. Part of the code sample is as below:

    app.get("/start", (req, res) => {
        const numberOfFigures = req.query.figures;
        const randomBaseNumber = Math.random();
        const theNumber = (randomBaseNumber * 10 ** numberOfFigures).toFixed(0);
        res.send(`guess the ${numberOfFigures} digit number!`);

    app.get("/guess", (req, res) => {
        let guessedNumber = req.query.guess;
        if (guessedNumber !== theNumber) {
            console.log("Wrong! Guess again");
        }

I am trying to use for instance theNumber value from /Start request in the /guess request!

Upvotes: 0

Views: 63

Answers (2)

Kaunaj Banerjee
Kaunaj Banerjee

Reputation: 51

The following 3 ways of storing data come to mind:

  1. Declare theNumber as a global variable.
  2. Store the variable in a json and import it when needed (eg: fs module).
  3. Store it in a database (eg: MongoDB).

Method 1 is the easiest way. The variable will be accessible from all the routes, and it will be erased if your app restarts.

let theNumber = 0;
...
app.get("/start", (req, res) => {
    theNumber = ...
    ...

Methods 2 and 3 will make the variable, once created, persist even if the app restarts. However, for this simple use case, I'd say they're overkill.

Upvotes: 0

Vulwsztyn
Vulwsztyn

Reputation: 2261

You need to keep theNumber variable outside of the scope of both callbacks e.g.

    let theNumber = 0
    app.get("/start", (req, res) => {
        const numberOfFigures = req.query.figures;
        const randomBaseNumber = Math.random();
        theNumber = (randomBaseNumber * 10 ** numberOfFigures).toFixed(0);
        res.send(`guess the ${numberOfFigures} digit number!`);

    app.get("/guess", (req, res) => {
        let guessedNumber = req.query.guess;
        if (guessedNumber !== theNumber) {
            console.log("Wrong! Guess again");
        }

I would also use POST for the /guess endpoint

Upvotes: 0

Related Questions